Taro Logo

Reverse Words in a String

#2 Most AskedMedium
3 views
Topics:
Strings

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 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.

Example 1:

Input: s = "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: s = "  hello world  "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: s = "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Constraints:

  • 1 <= s.length <= 104
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.

Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the input string contain leading, trailing, or multiple consecutive spaces between words that need to be cleaned up in the output?
  2. How should I handle an input string that is empty or consists entirely of spaces?
  3. Are we guaranteed that the input string will contain at least one valid word?
  4. Should the reversal be performed in-place (mutating the input if allowed by the language), or is returning a new string expected?
  5. Can I use built-in language functions and libraries like split() and join(), or should I implement the string manipulation from scratch using pointers?

Brute Force Solution

Approach

Imagine looking at a sentence written backward and wanting to flip the order of the words while cleaning up any messy spaces. The brute force strategy involves going through the text from right to left, picking out each word one by one, and placing them in a brand new line in that reversed order.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very end of the text to find the final word.
  2. Carefully copy that final word and set it aside as the beginning of your new answer.
  3. Scan backward through the text to find the next word right before the one you just copied.
  4. Copy that second word and place it directly after your first copied word, making sure to leave just a single standard space between them.
  5. Repeat this process of searching backward, copying each word, and adding it to your growing new text until you reach the very beginning of the original sentence.
  6. Finally, review your newly built text to make sure no extra spaces accidentally snuck into the front or the back.

Code Implementation

def reverse_words_brute_force(input_string):    collected_words = []    string_length = len(input_string)    pointer_index = string_length - 1    # Traverse backwards to isolate words from right to left while ignoring extra spacing    while pointer_index >= 0:        if input_string[pointer_index] == ' ':            pointer_index -= 1            continue        end_of_word = pointer_index        while pointer_index >= 0 and input_string[pointer_index] != ' ':            pointer_index -= 1        extracted_word = input_string[pointer_index + 1:end_of_word + 1]        collected_words.append(extracted_word)    # Join the reversed words with a single space to clean up any messy original padding    final_reversed_sentence = ' '.join(collected_words)    return final_reversed_sentence

Big(O) Analysis

Time Complexity
O(n) – To reverse the words and clean up the spaces, we traverse the input string of size n from right to left to locate and extract each word. Building the final result requires copying characters and words proportional to the length of the string, meaning each character is processed a constant number of times. This repetitive scanning and copying scales linearly, leading to approximately n operations in total. Simplifying this exact count of operations yields a final time complexity of O(n).
Space Complexity
O(N) – The brute force strategy described requires gathering and storing intermediate results in a new text structure, where N represents the total length of the input string. Specifically, scanning backward and copying words demands temporary data storage that scales proportionally with the size of the input. As the input size N increases, the extra memory allocated to build the newly reversed sentence grows linearly. Ultimately, this leads to an auxiliary space complexity of O(N).

Optimal Solution

Approach

Instead of trying to move entire words around while dealing with messy extra spaces, the optimal approach cleans up the text and flips the entire sentence backward. Afterward, it simply goes through the flipped text to restore each individual word back to its correct orientation.

Here's how the algorithm would work step-by-step:

  1. First, clean up the text by removing any accidental extra spaces at the very beginning, at the very end, and any excessive gaps stuck between the words.
  2. Next, take the entire cleaned message and flip it completely backward, so the final word becomes the first, the second-to-last becomes the second, and so on.
  3. Because flipping the entire message also flipped the letters inside each individual word, the words themselves currently look backward.
  4. Go through the flipped message and look for the individual words one by one.
  5. Flip each individual word right-side-up again so it reads normally, while keeping the correct new order of the words relative to each other.
  6. Once all the individual words are successfully corrected, you are left with a perfectly spaced sentence where the word order is completely reversed.

Code Implementation

class Solution:
    def reverseWords(self, original_string: str) -> str:
        # Convert string to list of characters because Python strings are immutable.
        char_list = []
        string_length = len(original_string)
        pointer = 0
        
        while pointer < string_length and original_string[pointer] == ' ':
            pointer += 1
            
        while pointer < string_length:
            if original_string[pointer] != ' ':
                if char_list and char_list[-1] != ' ':
                    char_list.append(original_string[pointer])
                elif char_list and char_list[-1] == ' ':
                    char_list.append(original_string[pointer])
                else:
                    char_list.append(original_string[pointer])
            elif char_list and char_list[-1] != ' ':
                char_list.append(' ')
            pointer += 1
            
        if char_list and char_list[-1] == ' ':
            char_list.pop()
            
        # Reverse the entire character array to place words in the correct reverse order.
        left_index = 0
        right_index = len(char_list) - 1
        while left_index < right_index:
            char_list[left_index], char_list[right_index] = char_list[right_index], char_list[left_index]
            left_index += 1
            right_index -= 1
            
        # Reverse each individual word back to normal orientation while maintaining word order.
        word_start = 0
        array_length = len(char_list)
        for word_end in range(array_length + 1):
            if word_end == array_length or char_list[word_end] == ' ':
                sub_left = word_start
                sub_right = word_end - 1
                while sub_left < sub_right:
                    char_list[sub_left], char_list[sub_right] = char_list[sub_right], char_list[sub_left]
                    sub_left += 1
                    sub_right -= 1
                word_start = word_end + 1
                
        return "".join(char_list)

Big(O) Analysis

Time Complexity
O(n) – Let n be the length of the input string. The process begins with a clean-up pass that iterates through the string once to remove unnecessary spaces. Next, the algorithm reverses the entire cleaned string, and subsequently iterates through it to reverse each individual word back to its correct orientation. Each of these distinct phases, including trimming, full reversal, and word-by-word reversal, visits the characters a constant number of times. This linear progression results in approximately 3n operations, which simplifies to Big O of n.
Space Complexity
O(N) – To clean up the text and manipulate the characters without violating immutability, the algorithm converts the input string of size N into a mutable auxiliary character array of size N. The subsequent steps, including reversing the entire sentence and individual words, are performed in place using only a few constant-space pointers and variables. Because the mutable character array is the only data structure that grows directly with the input size, the auxiliary space complexity scales linearly with the input string length N. Therefore, simplifying this memory usage to Big O notation results in O(N) space.

Edge Cases

String with leading or trailing spaces
How to Handle:
Trimming operations or pointer adjustments ignore these extraneous spaces during word extraction.
Multiple consecutive spaces between words
How to Handle:
Split or parsing logic treats multiple spaces as a single delimiter to prevent empty tokens.
String containing only spaces
How to Handle:
The algorithm filters out empty strings and returns an empty result cleanly.
Single word with no spaces
How to Handle:
The input is returned as-is after stripping any accidental boundary whitespace.
Extremely large string with thousands of words
How to Handle:
Linear time complexity ensures efficient memory usage and execution without hitting performance bottlenecks.
String with special characters or punctuation attached to words
How to Handle:
Characters are treated as part of the word tokens and preserved in their relative positions.
0/3 completed