Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Reverse Words in a String | Leetcode 151 | Split and Reverse Approach
    Data Structures & Algorithms

    Reverse Words in a String | Leetcode 151 | Split and Reverse Approach

    codeanddebugBy codeanddebug1 September 2025No Comments3 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of a question to solve Reverse Words in a String
    Share
    Facebook Twitter LinkedIn Pinterest Email

    You are given a string s that consists of words separated by spaces.

    • A word is defined as a sequence of non-space characters.
    • Your task is to reverse the order of words in the string.
    • Note that extra spaces between words should be reduced to just a single space in the final output, and there should be no leading or trailing spaces.

    Here’s the [Problem Link] to begin with.


    Examples

    Example 1

    Input:  s = "the sky is blue"
    Output: "blue is sky the"
    Explanation: Words are reversed in order.

    Example 2

    Input:  s = "  hello   world  "
    Output: "world hello"
    Explanation: Extra spaces are removed, and words are reversed.

    Example 3

    Input:  s = "a good   example"
    Output: "example good a"
    Explanation: Multiple spaces shrink to one.

    Intuition and Approach

    This problem requires reversing words while handling spaces properly. The key points are:

    1. Splitting the string into words:
      • Python’s split() function splits on whitespace and automatically removes extra spaces.
      • For example: " hello world ".split() → ["hello", "world"].
    2. Reversing the list of words:
      • Once we have the words in a list, we need to reverse their order.
      • For example: ["the", "sky", "is", "blue"] → ["blue", "is", "sky", "the"].
    3. Joining the words back into a single string:
      • Use " ".join(words) to form the reversed sentence.
      • Ensures that words are separated by exactly one space.

    Code Implementation

    class Solution:
        def reverseWords(self, s: str) -> str:
            words = s.split()          # Step 1: Split string into words, removes extra spaces
            res = []
    
            # Step 2: Traverse words in reverse order
            for i in range(len(words) - 1, -1, -1):
                res.append(words[i])
                if i != 0:             # Add a space between words
                    res.append(" ")
    
            # Step 3: Join characters into final string
            return "".join(res)

    Code Explanation

    1. words = s.split()
      • Splits s into a list of words.
      • Removes unnecessary leading, trailing, or multiple spaces.
    2. Reversing with loop:
      • Iterates from the last word to the first.
      • Adds each word to res.
      • Adds a space " " between words (but not after the last word).
    3. "".join(res)
      • Joins the list of words and spaces into a single string.

    So the sentence gets reconstructed in reversed order with proper spacing.


    Dry Run

    Input: s = " hello world "

    1. s.split() → ["hello", "world"]
    2. Loop in reverse:
      • Add "world" → res = [“world”]
      • Add space " " → res = [“world”, ” “]
      • Add "hello" → res = [“world”, ” “, “hello”]
    3. "".join(res) → "world hello"

    Final output: "world hello"


    Time and Space Complexity

    • Time Complexity:
      • Splitting the string → O(N)
      • Reversing and joining → O(N)
        Overall: O(N), where N is the length of the string.
    • Space Complexity:
      • Extra space for storing words → O(N)
      • Result array → O(N)
        Overall: O(N)

    Conclusion

    The Reverse Words in a String problem can be efficiently solved by:

    1. Splitting the string into words (removing extra spaces automatically).
    2. Reversing the word order.
    3. Joining them back with exactly one space.

    This approach runs in O(N) time and is simple, clean, and highly effective.

    This problem is commonly asked in coding interviews to test string manipulation and handling of edge cases like extra spaces.


    Join our Advance DSA COURSE

    For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    Easy Strings
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleRemove Outermost Parentheses | Leetcode 1021 | Stack Depth Counting Solution
    Next Article Largest Odd Number in String | Leetcode 1903 | Step-by-Step Solution Explained
    codeanddebug
    • Website

    Related Posts

    Data Structures & Algorithms

    Symmetric Tree | Leetcode 101 | Recursive DFS Approach

    2 September 2025
    Data Structures & Algorithms

    Binary Tree Right Side View | Leetcode 199 | BFS and DFS Approaches

    2 September 2025
    Data Structures & Algorithms

    Bottom View of Binary Tree | BFS with Horizontal Distance Mapping

    2 September 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • Data Structures & Algorithms (240)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Uncategorised (1)
    Recent Posts

    Symmetric Tree | Leetcode 101 | Recursive DFS Approach

    2 September 2025

    Binary Tree Right Side View | Leetcode 199 | BFS and DFS Approaches

    2 September 2025

    Bottom View of Binary Tree | BFS with Horizontal Distance Mapping

    2 September 2025

    Top View of Binary Tree | BFS with Horizontal Distance Mapping

    2 September 2025

    Vertical Order Traversal of a Binary Tree | Leetcode 987 | BFS + Sorting Solution

    2 September 2025
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.