Reverse Words in a String

MediumStrings · Two Pointers🧩 String ManipulationLeetCode #151 ↗Updated

Problem

A string s holds words (runs of non-space characters) separated by one or more spaces, possibly with leading/trailing spaces. Return the words in reverse order, joined by exactly one space, with no spaces at either end. The letters inside each word keep their order.
Input"the sky is blue"Output"blue is sky the"
Input" hello world "Output"world hello"
Input"a good example"Output"example good a"

1 ≤ s.length ≤ 104  ·  letters, digits, spaces  ·  at least one word  ·  Follow-up: O(1) extra space if the string were mutable.

Try it yourself

Java
class Solution {
    public String reverseWords(String s) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Reversing the whole string puts the words in the right order but spells each one backwards — so reverse each word again, then squeeze the spaces.
PatternString Manipulation

Instinct Reading, comparing or rebuilding text character by character? Walk indices on a char[] and build output with a StringBuilder, never with + in a loop.

Memory hack Chars in an array, pointers on the ends, builder at the back - strings are just arrays wearing a costume.

Open the String Manipulation guide →

Approaches

Brute ForceSplit & Join (Built-ins)

Time O(n)Space O(n)

trim() removes outer spaces and split("\\s+") treats any run of spaces as one separator, so we get exactly the words. Append them from last to first with single spaces.

Java
public String reverseWords(String s) {
    String[] words = s.trim().split("\\s+");
    StringBuilder reversed = new StringBuilder();
    for (int i = words.length - 1; i >= 0; i--) {
        reversed.append(words[i]);
        if (i != 0) reversed.append(' ');
    }
    return reversed.toString();
}

Shortest code, but leans on regex/library calls an interviewer may forbid.

At a glance

LevelApproachTimeSpace
Brute ForceSplit & Join (Built-ins)O(n)O(n)
BetterManual Scan + DequeO(n)O(n)
OptimalReverse All, Reverse Each Word, CompactO(n)O(n)*
Common pitfalls
  • split(" ") keeps empty strings for repeated spaces → double spaces in output.
  • Forgetting to flush the last word (no trailing space ends it).
  • Leaving a trailing space when the input ends with spaces — only add a gap if a word follows.
Interview tips
  • Ask whether built-ins like split are allowed before relying on them.
  • Explain the two-reversal trick; it also solves Rotate Array.
  • Be honest about Java: O(1) extra space only beyond the char[] copy.
Pattern
Double reversal + read/write pointers → reorder blocks of a sequence in-place (words, rotations).
My notes saved in this browser