{"id":12201,"date":"2026-04-15T00:00:10","date_gmt":"2026-04-14T18:30:10","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=12201"},"modified":"2026-04-15T11:53:42","modified_gmt":"2026-04-15T06:23:42","slug":"reverse-words-in-a-string","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/reverse-words-in-a-string\/","title":{"rendered":"Reverse Words in a String"},"content":{"rendered":"\n\n<link\n    href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\"\n    rel=\"stylesheet\"\n\/>\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_theme {\n  --primary: #E58C32;\n  --secondary: #030302;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2 {\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\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}\n\n.wp_blog_explanation code {\n  background: #fef9f4;   \/* light bg instead of dark blue *\/\n  color: #E58C32;        \/* brand orange *\/\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n  font-weight: 600;      \/* optional, makes it pop *\/\n}\n\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);\n}\n\n\/* Tab Buttons *\/\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 var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\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  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n\n\/* Dark mode variables *\/\n.wp_blog_theme.dark-mode {\n  --light-bg: #121212;\n  --text-dark: #f5f5f5;\n  --shadow: 0 4px 12px rgba(255, 255, 255, 0.08);\n  --code-bg: #1e1e1e;\n  --code-text: #c5f0ff;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_explanation {\n  background: #1e1e1e;\n}\n\n\/* Dark mode code highlight *\/\n.wp_blog_theme.dark-mode .wp_blog_explanation code {\n  background: #333;\n  color: #ffd27f;\n}\n\n.wp_blog_theme {\n  position: relative; \/* makes it the reference for absolute children *\/\n}\n\n.wp_blog_toggle-btn {\n  position: absolute;\n  top: 1rem;\n  right: 1rem;\n  z-index: 9999;\n  padding: 0.5rem 0.8rem;\n  border-radius: 10%;\n  background: var(--primary);\n  color: white;\n  font-weight: bold;\n  cursor: pointer;\n  border: none;\n  box-shadow: var(--shadow);\n  transition: background 0.3s, transform 0.2s;\n}\n\n.wp_blog_toggle-btn:hover {\n  background: #cc772e;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_code-tabs-container {\n  background: #1e1e1e;\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\"> \n      <button id=\"blogNotesThemeToggle\" class=\"wp_blog_toggle-btn\">\ud83c\udf19<\/button>\n    <h1 class=\"wp_blog_main-heading\"><\/h1>\n    <div class=\"wp_blog_explanation\">\n        <h2>Problem Statement:<\/h2>\n        <p>\n            Given an input <code>string s<\/code>, reverse the <strong>order of the words<\/strong>.\n        <\/p>\n        <p>\n            A <strong>word is defined as a sequence of non-space characters<\/strong>. The <code>words<\/code> in <code>s<\/code> will be separated by at least one space.\n        <\/p>\n\n        <strong>\n        <p>\n           Return <i>a string of the words in reverse order<\/i> concatenated by a single space. \n        <\/p>\n        <\/strong>\n\n        <p>\n            <strong>Note<\/strong> that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.\n        <\/p>\n                <h2>Examples:<\/h2>\n\n                <h3>Example 1:<\/h3>\n                <p><strong>Input:<\/strong> s = &#8220;the sky is blue&#8221;\n                <\/p>\n                <p><strong>Output:<\/strong> &#8220;blue is sky the&#8221;<\/p>\n                <!-- <p>\n                  <code>Explanation:<\/code>\n                  Drop the egg from floor 1. If it breaks, we know that f = 0.\n                    Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1.\n                    If it does not break, then we know f = 2.\n                    Hence, we need at minimum 2 moves to determine with certainty what the value of f is.\n                <\/p> -->\n\n\n                <h3>Example 2:<\/h3>\n                <p><strong>Input:<\/strong> s = &#8221;  hello world  &#8220;<\/p>\n\n                <p><strong>Output:<\/strong> &#8220;world hello&#8221;<\/p>\n                <p><strong>Explanation:<\/strong> Your reversed string should not contain leading or trailing spaces.<\/p>\n\n                <h3>Example 3:<\/h3>\n                <p><strong>Input:<\/strong> s = &#8220;a good   example&#8221;<\/p>\n\n                <p><strong>Output:<\/strong> &#8220;example good a&#8221;<\/p> \n                <p><strong>Explanation:<\/strong> You need to reduce multiple spaces between two words to a single space in the reversed string.<\/p>\n        \n\n                <!-- <h5>Example 3:<\/h5>\n                <p><strong>Input:<\/strong>\n                <\/p>\n                <p>\n                    nums1 = [0], m = 0\n                    nums2 = [1], n = 1\n                <\/p>    \n                <p><strong>Output:<\/strong>[1]<\/p>\n                  <p>\n                  <code>Explanation:<\/code>\n                 The arrays we are merging are [] and [1].\n                    The result of the merge is [1].\n                    Note that because m = 0, there are no elements in nums1. \n                    The 0 is only there to ensure the merge result can fit in nums1.\n                <\/p> -->\n\n                <h2>Constraints<\/h2>\n                <p><code>1 <= s.length <= 10<sup>4<\/sup><\/code><\/p>\n                <p><code>\n                  <code>s<\/code> contains English letters (upper-case and lower-case), digits, and spaces <code>' '<\/code>.\n                <\/code><\/p>\n                <p>There is at least one word in <code>s<\/code>.<\/p>\n\n                    <h2>Time Complexity:<\/h2>\n                    <li>\n                      <p><strong>Time Complexity = O(n)<\/strong>\n                      <\/li>\n                    <h2>Space Complexity:<\/h2>\n                    <li>\n                      <p><strong>Space Complexity = O(n)<\/strong><\/p>\n                    <\/li>\n\n                <!-- <h2>Approach<\/h2>\n                <ul>\n                    <li><strong>Trim the string<\/strong> \u2192 remove leading & trailing <code>spaces<\/code>.<\/li>\n                    <li><code>Traverse<\/code> character by <strong>character<\/strong>.<\/li>\n                    <li>Next, <strong>Build<\/strong> each word.<\/li>\n                    <li>When a <code>space is found:<\/code>\n                        <ul>\n                            <li><strong>Push the word<\/strong> to the front (reverse order).<\/li>\n                            <li><code>Reset<\/code> Word.<\/li>\n                        <\/ul>\n                    <\/li>\n                    <li>Add the <strong>last word after loop<\/strong> and Join words <code>with single space<\/code>.<\/li>\n                <\/ul> -->\n\n                <h2>Approach<\/h2>\n<ul>\n    <li>\n        <strong>Trim the string<\/strong> \u2192 First, remove all leading and trailing <code>spaces<\/code> from the given string to avoid unnecessary empty words at the beginning or end.\n    <\/li>\n\n    <li>\n        <strong>Initialize variables<\/strong> \u2192 Create an empty <code>result<\/code> array (or list) to store words in reverse order and a temporary <code>word<\/code> string to build characters.\n    <\/li>\n\n    <li>\n        <code>Traverse<\/code> the string <strong>character by character<\/strong> \u2192 Iterate through each character of the string from left to right.\n    <\/li>\n\n    <li>\n        <strong>Build each word<\/strong> \u2192 \n        <ul>\n            <li>If the current character is not a <code>space<\/code>, keep adding it to the <code>word<\/code> variable.<\/li>\n        <\/ul>\n    <\/li>\n\n    <li>\n        When a <code>space is found:<\/code>\n        <ul>\n            <li>Check if the current <code>word<\/code> is not empty.<\/li>\n            <li>If not empty, <strong>insert (push) the word at the front<\/strong> of the result to maintain reverse order.<\/li>\n            <li><code>Reset<\/code> the <code>word<\/code> to an empty string to start building the next word.<\/li>\n        <\/ul>\n    <\/li>\n\n    <li>\n        <strong>Handle the last word<\/strong> \u2192 After the loop ends, check if a word is still present in the <code>word<\/code> variable and add it to the front of the result.\n    <\/li>\n\n    <li>\n        <strong>Join words<\/strong> \u2192 Finally, combine all words in the result using a <code>single space<\/code> to form the reversed sentence.\n    <\/li>\n<\/ul>\n\n<h2>Dry Run<\/h2>\n<div style=\"background: var(--light-bg); border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0; color: var(--text-dark);\"> \n  <p><strong>Input:<\/strong> <code>s = \"  hello world  \"<\/code><\/p> \n  \n  <pre style=\"white-space: pre-wrap; background: var(--code-bg); padding: 1rem; border-radius: 8px; overflow-x: auto; color: var(--code-text);\">\nStep 1: Trim the string\n   s = s.trim()\n   \u2192 s = \"hello world\"\n\nInitial:\n   wordArray = []\n   word = \"\"\n\nStep 2: c = 'h'\n   c !== \" \" \u2192 word += 'h'\n   word = \"h\"\n\nStep 3: c = 'e'\n   word = \"he\"\n\nStep 4: c = 'l'\n   word = \"hel\"\n\nStep 5: c = 'l'\n   word = \"hell\"\n\nStep 6: c = 'o'\n   word = \"hello\"\n\nStep 7: c = ' '\n   c == \" \" and word.length > 0\n   \u2192 wordArray.unshift(\"hello\")\n   \u2192 wordArray = [\"hello\"]\n   \u2192 word = \"\"\n\nStep 8: c = 'w'\n   word = \"w\"\n\nStep 9: c = 'o'\n   word = \"wo\"\n\nStep 10: c = 'r'\n   word = \"wor\"\n\nStep 11: c = 'l'\n   word = \"worl\"\n\nStep 12: c = 'd'\n   word = \"world\"\n\nAfter loop ends:\n   word = \"world\" (last word)\n\nStep 13: Push last word\n   wordArray.unshift(\"world\")\n   \u2192 wordArray = [\"world\", \"hello\"]\n\nStep 14: Join array\n   wordArray.join(\" \")\n   \u2192 \"world hello\"\n  <\/pre> \n  \n  <p><strong>Output:<\/strong> <code>\"world hello\"<\/code><\/p> \n<\/div>\n<\/div>\n\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\">\n            JavaScript\n        <\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n        <pre><code class=\"language-javascript\">\nvar reverseWords = function(s) {\n    s = s.trim();\n\n    let wordArray = [];\n    let word = \"\";\n\n    for (let c of s) {\n        if (c !== \" \") {\n            word += c;\n        } else if (word.length > 0) {\n            wordArray.unshift(word);\n            word = \"\";\n        }\n    }\n\n    \/\/ push the last word\n    if (word.length > 0) {\n        wordArray.unshift(word);\n    }\n\n    return wordArray.join(\" \");\n};\n\n\n<h3>\/\/ Second Approach for JavaScript<\/h3>\n<i>\n    <strong>Note: <\/strong>\n    <p>\n        JavaScript makes string manipulation very concise and efficient because it \n        provides powerful built-in methods like <code>trim()<\/code>, \n        <code>split()<\/code>, <code>reverse()<\/code>, and <code>join()<\/code>.  <\/p>\n        \n    <p>\n        These allow us to solve the problem in just a few lines of code. In contrast, \n        languages like Java, C++, or C require more verbose implementations  due to \n        fewer direct utilities or the need for manual handling of strings. However, \n        the core logic remains the same across all languages \u2014 clean the string, \n        split it into words, reverse the order, and join them back together.\n    <\/p>\n<\/i>\n\ns = s.trim();\n\nlet words = s.split(\/\\s+\/); \nreturn words.reverse().join(\" \"); \n};\n\n\n    <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n        <pre><code class=\"language-python\">\ndef reverseWords(s: str) -> str:\n    s = s.strip()\n    \n    word_array = []\n    word = \"\"\n\n    for c in s:\n        if c != \" \":\n            word += c\n        elif word:\n            word_array.insert(0, word)\n            word = \"\"\n\n    if word:\n        word_array.insert(0, word)\n\n    return \" \".join(word_array)\n    <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n        <pre><code class=\"language-java\">\nclass Solution {\n    public String reverseWords(String s) {\n        s = s.trim();\n\n        LinkedList<String> wordArray = new LinkedList<>();\n        String word = \"\";\n\n        for (char c : s.toCharArray()) {\n            if (c != ' ') {\n                word += c;\n            } else if (word.length() > 0) {\n                wordArray.addFirst(word);\n                word = \"\";\n            }\n        }\n\n        if (word.length() > 0) {\n            wordArray.addFirst(word);\n        }\n\n        return String.join(\" \", wordArray);\n    }\n}\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n        <pre><code class=\"language-cpp\">\nclass Solution {\npublic:\n    string reverseWords(string s) {\n        vector<string> wordArray;\n        string word = \"\";\n\n        \/\/ trim manually\n        int i = 0, j = s.size() - 1;\n        while (i <= j &#038;&#038; s[i] == ' ') i++;\n        while (j >= i && s[j] == ' ') j--;\n\n        for (int k = i; k <= j; k++) {\n            if (s[k] != ' ') {\n                word += s[k];\n            } else if (!word.empty()) {\n                wordArray.insert(wordArray.begin(), word);\n                word = \"\";\n            }\n        }\n\n        if (!word.empty()) {\n            wordArray.insert(wordArray.begin(), word);\n        }\n\n        string result = \"\";\n        for (int i = 0; i < wordArray.size(); i++) {\n            result += wordArray[i];\n            if (i != wordArray.size() - 1) result += \" \";\n        }\n\n        return result;\n    }\n};\n    <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n        <pre><code class=\"language-c\">\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\n\nchar* reverseWords(char* s) {\n    int n = strlen(s);\n    char** words = (char**)malloc(n * sizeof(char*));\n    int count = 0;\n\n    char word[1000];\n    int w = 0;\n\n    for (int i = 0; i <= n; i++) {\n        if (s[i] != ' ' &#038;&#038; s[i] != '\\0') {\n            word[w++] = s[i];\n        } else if (w > 0) {\n            word[w] = '\\0';\n            words[count] = (char*)malloc((w + 1) * sizeof(char));\n            strcpy(words[count], word);\n            count++;\n            w = 0;\n        }\n    }\n\n    char* result = (char*)malloc(n + 1);\n    result[0] = '\\0';\n\n    for (int i = count - 1; i >= 0; i--) {\n        strcat(result, words[i]);\n        if (i != 0) strcat(result, \" \");\n    }\n\n    return result;\n}\n   <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n        <pre><code class=\"language-csharp\">\nusing System;\nusing System.Collections.Generic;\n\npublic class Solution {\n    public string ReverseWords(string s) {\n        s = s.Trim();\n\n        LinkedList<string> wordArray = new LinkedList<string>();\n        string word = \"\";\n\n        foreach (char c in s) {\n            if (c != ' ') {\n                word += c;\n            } else if (word.Length > 0) {\n                wordArray.AddFirst(word);\n                word = \"\";\n            }\n        }\n\n        if (word.Length > 0) {\n            wordArray.AddFirst(word);\n        }\n\n        return string.Join(\" \", wordArray);\n    }\n}\n  <\/code><\/pre>\n    <\/div>\n<\/div>\n<\/div>\n\n<script>\ndocument.addEventListener(\"DOMContentLoaded\", () => {\n  const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n  const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n  buttons.forEach((button) => {\n    button.addEventListener(\"click\", () => {\n      const lang = button.getAttribute(\"data-lang\");\n\n      buttons.forEach((btn) => btn.classList.remove(\"active\"));\n      contents.forEach((content) => content.classList.remove(\"active\"));\n\n      button.classList.add(\"active\");\n      document\n        .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n        .classList.add(\"active\");\n    });\n  });\n\n  const themeToggle = document.getElementById(\"blogNotesThemeToggle\");\n  const themeContainer = document.querySelector(\".wp_blog_theme\");\n\n  themeToggle.addEventListener(\"click\", () => {\n    themeContainer.classList.toggle(\"dark-mode\");\n    themeToggle.textContent =\n      themeContainer.classList.contains(\"dark-mode\") ? \"\u2600\ufe0f\" : \"\ud83c\udf19\";\n  });\n});\n<\/script>\n\n\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udf19 Problem Statement: Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain<\/p>\n","protected":false},"author":108,"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":[210,322,260,176,175,811,174,172,173],"tags":[],"class_list":["post-12201","post","type-post","status-publish","format-standard","category-algorithms","category-algorithms-and-data-structures","category-c-c-plus-plus","category-csharp","category-cplusplus","category-data-structures-and-algorithms","category-java","category-javascript","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/12201","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\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=12201"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/12201\/revisions"}],"predecessor-version":[{"id":12202,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/12201\/revisions\/12202"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=12201"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=12201"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=12201"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}