{"id":7304,"date":"2025-06-26T19:19:36","date_gmt":"2025-06-26T13:49:36","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=7304"},"modified":"2025-06-26T19:19:37","modified_gmt":"2025-06-26T13:49:37","slug":"find-the-length-of-last-word-using-two-loops","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/find-the-length-of-last-word-using-two-loops\/","title":{"rendered":"Find the length of last word using two loops"},"content":{"rendered":"\n<!-- PrismJS for Syntax Highlighting -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\" rel=\"stylesheet\">\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n  .wp_blog_main-heading {\n    text-align: center;\n    font-size: 2.4rem;\n    color: #E58C32;\n    margin-top: 2.5rem;\n    font-weight: bold;\n  }\n\n  .wp_blog_explanation,\n  .wp_blog_code-tabs-container {\n    max-width: 940px;\n    margin: 2rem auto;\n    padding: 2rem;\n    border-radius: 12px;\n    background-color: #f9fafb;\n  }\n\n  .wp_blog_explanation h2 {\n    font-size: 1.4rem;\n    color: #E58C32;\n    margin-bottom: 0.75rem;\n  }\n\n  .wp_blog_explanation p,\n  .wp_blog_explanation li {\n    font-size: 1.05rem;\n    line-height: 1.7;\n    margin: 0.5rem 0;\n    color: #1f2937;\n  }\n\n  .wp_blog_explanation code {\n    padding: 3px 6px;\n    border-radius: 4px;\n    background: #e5e7eb;\n    font-family: 'Courier New', monospace;\n  }\n\n  .wp_blog_code-tabs-header {\n    display: flex;\n    flex-wrap: wrap;\n    gap: 0.5rem;\n    margin-bottom: 1rem;\n  }\n\n  .wp_blog_code-tab-button {\n    padding: 0.6rem 1.2rem;\n    border: 1px solid #E58C32;\n    color: #E58C32;\n    border-radius: 50px;\n    font-weight: 600;\n    cursor: pointer;\n    background-color: white;\n    transition: background 0.3s ease, color 0.3s ease;\n  }\n\n  .wp_blog_code-tab-button.active {\n    background: #E58C32;\n    color: white;\n  }\n\n  .wp_blog_code-tab-content {\n    display: none;\n    background: #111827;\n    border-radius: 12px;\n  }\n\n  .wp_blog_code-tab-content.active {\n    display: block;\n  }\n\n  .wp_blog_code-tab-content pre {\n    margin: 0;\n    padding: 1.5rem;\n    font-size: 1rem;\n    overflow-x: auto;\n    color: #f3f4f6;\n    background: #111827;\n    border-radius: 12px;\n  }\n<\/style>\n\n<div class=\"wp_blog_explanation\">\n  <h2>Problem Statement:<\/h2>\n  <p>Given a string <code>s<\/code> consisting of words and spaces, return the length of the last word in the string.<\/p>\n  <p>A word is defined as a maximal substring consisting of non-space characters only.<\/p>\n\n  <h2>Example:<\/h2>\n  <p><strong>Input:<\/strong> s = &#8220;Hello World&#8221;<br><strong>Output:<\/strong> 5<br><em>The last word is &#8220;World&#8221; with length 5.<\/em><\/p>\n  <p><strong>Input:<\/strong> s = &#8221;   fly me   to   the moon  &#8220;<br><strong>Output:<\/strong> 4<br><em>The last word is &#8220;moon&#8221; with length 4.<\/em><\/p>\n  <p><strong>Input:<\/strong> s = &#8220;luffy is still joyboy&#8221;<br><strong>Output:<\/strong> 6<br><em>The last word is &#8220;joyboy&#8221; with length 6.<\/em><\/p>\n\n  <h2>Constraints:<\/h2>\n  <ul>\n    <li>1 \u2264 s.length \u2264 10<sup>4<\/sup><\/li>\n    <li>s consists of only English letters and spaces <code>' '<\/code><\/li>\n    <li>There will be at least one word in <code>s<\/code><\/li>\n  <\/ul>\n\n  <h2>Approach:<\/h2>\n  <ul>\n    <li>Start from the end of the string and skip any trailing spaces.<\/li>\n    <li>Count the number of characters in the last word until a space or the beginning of the string is reached.<\/li>\n    <li>This ensures we efficiently find the last word without extra space.<\/li>\n  <\/ul>\n\n  <h2>Time and Space Complexity:<\/h2>\n  <ul>\n    <li><strong>Time Complexity:<\/strong> O(n) \u2014 Traverse the string once from the end.<\/li>\n    <li><strong>Space Complexity:<\/strong> O(1) \u2014 No extra space used apart from counters.<\/li>\n  <\/ul>\n<\/div>\n\n<div class=\"wp_blog_code-tabs-container\">\n  <div class=\"wp_blog_code-tabs-header\">\n    <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"csharp\">C#<\/button>\n  <\/div>\n\n  <!-- JavaScript -->\n  <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n    <pre><code class=\"language-javascript\">\nvar lengthOfLastWord = function(s) {\n    let n = s.length - 1;\n    while (n >= 0 && s[n] === ' ') n--;\n\n    let count = 0;\n    while (n >= 0 && s[n] !== ' ') {\n        count++;\n        n--;\n    }\n\n    return count;\n};\n    <\/code><\/pre>\n  <\/div>\n\n  <!-- C -->\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n    <pre><code class=\"language-c\">\nint lengthOfLastWord(char* s) {\n    int len = strlen(s);\n    int i = len - 1, count = 0;\n\n    while (i >= 0 && s[i] == ' ') i--;\n    while (i >= 0 && s[i] != ' ') {\n        count++;\n        i--;\n    }\n\n    return count;\n}\n    <\/code><\/pre>\n  <\/div>\n\n  <!-- C++ -->\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n    <pre><code class=\"language-cpp\">\nclass Solution {\npublic:\n    int lengthOfLastWord(string s) {\n        int i = s.length() - 1, count = 0;\n\n        while (i >= 0 && s[i] == ' ') i--;\n        while (i >= 0 && s[i] != ' ') {\n            count++;\n            i--;\n        }\n\n        return count;\n    }\n};\n    <\/code><\/pre>\n  <\/div>\n\n  <!-- Java -->\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n    <pre><code class=\"language-java\">\nclass Solution {\n    public int lengthOfLastWord(String s) {\n        int i = s.length() - 1, count = 0;\n\n        while (i >= 0 && s.charAt(i) == ' ') i--;\n        while (i >= 0 && s.charAt(i) != ' ') {\n            count++;\n            i--;\n        }\n\n        return count;\n    }\n}\n    <\/code><\/pre>\n  <\/div>\n\n  <!-- Python -->\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n    <pre><code class=\"language-python\">\nclass Solution(object):\n    def lengthOfLastWord(self, s):\n        i = len(s) - 1\n        while i >= 0 and s[i] == ' ':\n            i -= 1\n\n        count = 0\n        while i >= 0 and s[i] != ' ':\n            count += 1\n            i -= 1\n\n        return count\n    <\/code><\/pre>\n  <\/div>\n\n  <!-- C# -->\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"csharp\">\n    <pre><code class=\"language-csharp\">\npublic class Solution {\n    public int LengthOfLastWord(string s) {\n        int i = s.Length - 1, count = 0;\n\n        while (i >= 0 && s[i] == ' ') i--;\n        while (i >= 0 && s[i] != ' ') {\n            count++;\n            i--;\n        }\n\n        return count;\n    }\n}\n    <\/code><\/pre>\n  <\/div>\n<\/div>\n\n<script>\n  document.addEventListener('DOMContentLoaded', () => {\n    const buttons = document.querySelectorAll('.wp_blog_code-tab-button');\n    const contents = document.querySelectorAll('.wp_blog_code-tab-content');\n    buttons.forEach(button => {\n      button.addEventListener('click', () => {\n        const lang = button.getAttribute('data-lang');\n        buttons.forEach(btn => btn.classList.remove('active'));\n        contents.forEach(content => content.classList.remove('active'));\n        button.classList.add('active');\n        document.querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`).classList.add('active');\n      });\n    });\n  });\n<\/script>\n\n","protected":false},"excerpt":{"rendered":"<p>Problem Statement: Given a string s consisting of words and spaces, return the length of the last word in the string. A word is defined as a maximal substring consisting of non-space characters only. Example: Input: s = &#8220;Hello World&#8221;Output: 5The last word is &#8220;World&#8221; with length 5. Input: s = &#8221; fly me to<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[260,176,811,810,174,172,173],"tags":[],"class_list":["post-7304","post","type-post","status-publish","format-standard","category-c-c-plus-plus","category-csharp","category-data-structures-and-algorithms","category-dsa","category-java","category-javascript","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7304","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=7304"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7304\/revisions"}],"predecessor-version":[{"id":7305,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7304\/revisions\/7305"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=7304"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=7304"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=7304"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}