Reverse Words in a String · Optimal Solution

Three steps: normalize, reverse all, reverse each word.

A teleprompter script needs its sentence order flipped — the closing line read first — without rearranging individual words. Three in-place steps accomplish this: normalize extra whitespace, reverse the entire character array, then reverse each word individually. The words end up in reverse order with their internal letters restored. O(n) time. O(n) space for the character array.


Interactive

Watch the three-step pipeline transform the string


Concept

Why reversing twice restores letter order

Reversing the whole string puts words in the right order but spells each word backwards. A second pass reverses each word individually, fixing the letters while preserving the new word order.

Normalize

Trim leading and trailing spaces, collapse runs of multiple spaces into a single space. This gives a clean sequence of words separated by exactly one space.

Reverse all

Reverse the entire normalized string character by character. Words move to their final positions but each word is now spelled backwards.

Reverse each word

Walk through the reversed string, find each word's boundaries, and reverse it in place. This restores the correct spelling of every word.


Algorithm

Normalize, flip, restore

  1. 1

    Normalize the input

    Walk through the string, skip leading spaces, collapse consecutive spaces to one, and trim trailing spaces. Build a clean character array.

  2. 2

    Reverse the entire array

    Use two pointers at each end, swap characters inward until they meet. Every word is now in the correct position but spelled backwards.

  3. 3

    Reverse each individual word

    Scan for word boundaries (space-delimited). For each word, reverse its characters in place using two pointers. Letters are restored to correct order.


Edge Cases

Where spacing and length matter

Single word

After normalization only one word remains. Reversing the whole string spells it backwards, but the per-word reversal restores it immediately — output equals input.

Extra whitespace everywhere

Leading, trailing, and multiple interior spaces are all collapsed during normalization. The algorithm never needs to reason about irregular spacing after step one.

Single-character words

Words like "a b c" have nothing to reverse individually — the per-word reversal is a no-op for length-1 words. Only the full-string reversal matters.