Reverse Every Word in a String - Visualization

Visualization Player

Problem Statement

Given a string containing one or more words separated by spaces, your task is to reverse each word individually, while keeping the order of words the same.

Each word is defined as a sequence of characters separated by spaces. Spaces should be preserved between words, but the characters of each word should appear in reverse order.

This operation should not affect extra spaces or punctuation. The final result should be a single string with all words reversed.

Examples

Input String Output String Description
"hello world" "olleh dlrow" Each word is reversed individually
"data structures" "atad serutcurts" Two words reversed, order remains
" a b c " " a b c " Single-letter words are the same; spaces preserved
" hello world " " olleh dlrow " Multiple spaces between and around words are preserved
"example" "elpmaxe" Single word reversed
" " " " Only spaces, no words to reverse
"" "" Empty string returns empty string

Solution

Understanding the Problem

We are given a sentence made up of words separated by spaces. Our task is to reverse the characters of each word individually, but keep the word order and spacing exactly as in the original sentence.

In simple terms: "hello world" should become "olleh dlrow".

This might sound straightforward, but we have to be careful with extra spaces, punctuation, or special characters. The idea is not to rearrange the words, just reverse each one while preserving the overall structure of the sentence.

Step-by-Step Solution with Example

Step 1: Split the string into words

We start by breaking the input string based on spaces. However, if we use a regular split() function, it might collapse multiple spaces into one, which changes the formatting. So we need to find a way to preserve the spacing or use a manual method.

For example: Input: "hello world" Splitting normally gives: ["hello", "world"] — notice the double space is lost. We must preserve that structure.

Step 2: Reverse each word individually

Loop through each word and reverse its characters. For instance:

  • "hello""olleh"
  • "world""dlrow"

If we preserved spacing correctly in the previous step, we now replace each word with its reversed version in the same positions.

Step 3: Combine the reversed words with the correct spacing

After reversing each word, we reconstruct the sentence by joining them with the original spacing. If you’re manually processing characters and spaces, you can keep track of them using a loop.

For example: Original: "hello world" Reversed: "olleh dlrow" We preserved the double space!

Edge Cases

  • Empty string: If input is "", the output should also be "".
  • Only spaces: If input is " ", then output should also be " ". No words to reverse, but spacing must remain.
  • Single word: Input like "hello" should give "olleh".
  • Punctuation or symbols: If input has punctuation like "hello!", it becomes "!olleh". We treat symbols as part of the word.
  • Multiple spaces between words: We must ensure that all original spaces are retained exactly as they were.

Finally

This problem helps beginners learn about string manipulation, loops, and edge case handling. It also builds awareness of how certain built-in functions behave, especially with whitespace.

When solving string problems, always consider how the language’s functions treat whitespace, and whether they preserve or collapse it. Manual traversal often gives more control when formatting matters.

Practice with different kinds of inputs — clean sentences, extra spaces, empty strings, or symbols — to strengthen your understanding.

Algorithm Steps

  1. Split the input string using space as delimiter into a list of words.
  2. Iterate through each word in the list.
  3. For each word, reverse its characters using a loop or inbuilt reverse method.
  4. Join all the reversed words using a single space.
  5. Return the resulting string.

Code

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

void reverse(char* str, int start, int end) {
    while (start < end) {
        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }
}

void reverseEachWord(char* str) {
    int i = 0, start = 0;
    while (str[i]) {
        if (str[i] == ' ' || str[i + 1] == '\0') {
            int end = (str[i] == ' ') ? i - 1 : i;
            reverse(str, start, end);
            start = i + 1;
        }
        i++;
    }
}

int main() {
    char str[] = "Hello World";
    reverseEachWord(str);
    printf("Reversed: %s\n", str);
    return 0;
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)We scan each character in the string once during splitting, reversing, and joining.
Average CaseO(n)Each word is reversed individually, and all characters are processed linearly.
Worst CaseO(n)Even if the string has long words or many spaces, we still traverse each character only once.

Space Complexity

O(n)

Explanation: A new string is built to store the reversed output, proportional to the input size.


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