Reverse Words in a String - Visualization

Visualization Player

Problem Statement

Given a string s that contains words separated by spaces, reverse the order of words in the string.

Remove any leading or trailing spaces and reduce multiple spaces between words to a single space in the output.

Note: Do not reverse the characters of individual words—only the word order should be reversed.

Examples

Input Output Description
"the sky is blue" "blue is sky the" Words are reversed in order
" hello world " "world hello" Extra spaces removed and words reversed
"a good example" "example good a" Multiple spaces between words collapsed
" Bob Loves Alice " "Alice Loves Bob" Trimmed and reversed correctly

Solution

Understanding the Problem

We are given a string that contains words separated by spaces. However, the string may contain extra spaces — multiple spaces between words, or leading and trailing spaces. Our task is to reverse the order of the words and return a properly formatted string: the words should be in reverse order, and there should be exactly one space between them, with no leading or trailing spaces.

Step-by-Step Solution with Example

Let’s take the example string:

{ "array": [" the sky is blue "], "showIndices": false }

Step 1: Trim the String

We first remove the leading and trailing spaces from the string.

{ "array": ["the sky is blue"], "showIndices": false }

Step 2: Split the String by Spaces

Next, we split the string using space as the delimiter. This gives us an array of substrings. Some of these may be empty due to multiple spaces.

{ "array": ["the", "", "sky", "is", "blue"], "showIndices": false }

Step 3: Filter Out Empty Strings

We now remove the empty strings from the array, keeping only the valid words.

{ "array": ["the", "sky", "is", "blue"], "showIndices": false }

Step 4: Reverse the List of Words

We reverse the list so the words appear in reverse order.

{ "array": ["blue", "is", "sky", "the"], "showIndices": false }

Step 5: Join Words with a Single Space

Finally, we join the reversed words using a single space to form the final output string.

{ "array": ["blue is sky the"], "showIndices": false }

Edge Cases

  • Empty String: Return an empty string.
  • String with Only Spaces: After trimming and filtering, return an empty string.
  • String with One Word: Return the trimmed single word as-is.
  • Multiple Spaces Between Words: Ensure only one space between words in the final output.

Finally

This approach ensures a clean and efficient transformation of the input string. By trimming spaces, filtering out empty tokens, reversing the order, and rejoining the words, we handle both normal and edge cases gracefully. This makes the solution beginner-friendly and robust for real-world usage.

Algorithm Steps

  1. Trim leading and trailing spaces from the string s.
  2. Split the string into a list of words using whitespace as the delimiter.
  3. Filter out any empty strings caused by multiple spaces.
  4. Reverse the list of words.
  5. Join the words with a single space to form the final output.

Code

C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void reverseWords(char *str) {
    char *tokens[100];
    int count = 0;
    char *word = strtok(str, " ");
    while (word) {
        tokens[count++] = word;
        word = strtok(NULL, " ");
    }
    for (int i = count - 1; i >= 0; i--) {
        printf("%s", tokens[i]);
        if (i != 0) printf(" ");
    }
}

int main() {
    char str[] = "  hello   world  ";
    reverseWords(str);
    return 0;
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)Each character in the string is processed once during trimming, splitting, and joining.
Average CaseO(n)All operations—trim, split, reverse, and join—are linear with respect to the input size.
Worst CaseO(n)Even in the worst case with many extra spaces, we still process each character only once.

Space Complexity

O(n)

Explanation: We use extra space to store the list of words and the final result string.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...