Problem Walkthrough

Reverse Words in String LeetCode 151

Split by whitespace, reverse the list, and join with a single space — or use a two-pass in-place reversal to handle leading, trailing, and multiple spaces with O(1) extra space.

8 min read|

Reverse Words in String

LeetCode 151

Problem Overview

LeetCode 151 — Reverse Words in a String gives you a string s containing words separated by spaces (possibly multiple spaces) and asks you to return the words in reversed order with exactly one space between each word. Leading and trailing spaces must be removed from the output.

For example, " hello world " becomes "world hello". The word order flips, extra spaces vanish, and the result is a clean single-space-separated string. This is deceptively tricky because naive splits on a single space character produce empty strings wherever multiple spaces appear.

The constraints allow 1 <= s.length <= 10^4 and the string contains English letters, digits, and spaces. At least one word is guaranteed. The challenge is cleanly handling the three edge-case space scenarios: leading spaces, trailing spaces, and multiple consecutive spaces between words.

  • Input: string with words separated by one or more spaces
  • Output: words in reversed order, single space between each
  • Leading and trailing spaces must be stripped from the output
  • " hello world " → "world hello"
  • "a good example" → "example good a"
  • At least one word guaranteed; multiple consecutive spaces possible

Split-Reverse-Join

The cleanest approach is the split-reverse-join pipeline: split the string into words, reverse the list of words, and join them back with a single space. In Python this collapses to a one-liner: " ".join(s.split()[::-1]). The key is calling split() with no arguments.

In Java the equivalent is: String[] words = s.trim().split("\\s+"); then build a StringBuilder by iterating words in reverse. The trim() removes leading and trailing spaces, and "\\s+" as the regex matches any sequence of whitespace characters as a single delimiter, preventing empty strings in the array.

The time complexity is O(n) because splitting, reversing, and joining each make a single linear pass. Space complexity is O(n) for the array of words and the output string. This is the production-quality approach — clear, concise, and handles all edge cases without manual pointer manipulation.

💡

Python split() — The Ultimate Edge-Case Handler

Python's split() without arguments splits on ANY whitespace sequence and automatically removes empty strings caused by multiple consecutive spaces, leading spaces, and trailing spaces. This means " hello world ".split() returns ['hello', 'world'] with no empty strings and no trimming needed. One call eliminates all three edge cases simultaneously.

Why split() Handles Edge Cases

Understanding why Python split() without arguments is powerful requires knowing exactly what it does. Unlike split(" ") which splits only on a literal single space and produces empty strings for consecutive spaces, the no-argument form treats any sequence of whitespace as one delimiter.

Three edge cases eliminated in one call: leading spaces — split() ignores them and produces no empty string at the start; trailing spaces — split() ignores them and produces no empty string at the end; multiple spaces between words — split() treats the entire sequence as one delimiter and produces exactly one word per group.

The result is a clean list containing only the actual words, with no empty strings or whitespace artifacts. This is why " ".join(s.split()[::-1]) is considered the canonical Python solution — it is correct by construction regardless of how many spaces appear anywhere in the input.

  1. 1Leading spaces: split() ignores them — no empty string produced at the front
  2. 2Trailing spaces: split() ignores them — no empty string produced at the end
  3. 3Multiple spaces between words: treated as one delimiter — one word per group
  4. 4Result: a clean list containing only the actual word strings
  5. 5No need for strip(), replace(), or any preprocessing

In-Place Approach (O(1) Space)

The follow-up challenge asks for O(1) extra space. Because Python and Java strings are immutable this requires working with a character array. The in-place algorithm uses a beautiful double-reverse insight: reverse the entire string, then reverse each individual word, then clean up the extra spaces.

Step 1 — reverse the entire string: "hello world" becomes "dlrow olleh". Step 2 — reverse each word within the result: "world hello". The double reverse restores each word's internal letter order while keeping the words in reverse order relative to each other. Step 3 — compact extra spaces by scanning the array and writing non-space characters and single inter-word spaces to the front.

This approach is O(n) time and O(1) extra space (assuming a mutable character array). The three-step structure is elegant and demonstrates deep algorithmic understanding. The reversal trick generalizes to rotating arrays and other rearrangement problems, making it a valuable pattern to internalize.

ℹ️

The Double-Reverse Trick — Interviewers Love This

The in-place approach uses the double-reverse pattern: reverse everything, then reverse each part. This restores internal order while achieving the global rearrangement. It is more complex to implement correctly than split-reverse-join, but it achieves O(1) extra space. Interviewers frequently ask for this as a follow-up — presenting it proactively signals strong algorithmic depth.

Walk-Through Example

Trace " hello world " through the split-reverse-join pipeline step by step. The input has two leading spaces, one space between words, and two trailing spaces — a perfect example for demonstrating all three edge cases handled simultaneously.

After calling s.split(), the result is ["hello", "world"] — all spaces consumed, no empty strings. After [::-1] the list is ["world", "hello"]. After " ".join() the result is "world hello" — exactly one space between words, no leading or trailing spaces. Total: one line of code handles all edge cases.

For the in-place approach on the same input: step 1 reverse entire char array gives " dlrow olleh "; step 2 reverse each word gives " world hello "; step 3 compact spaces (remove leading/trailing and collapse internal multiples) gives "world hello". Both approaches produce the same correct output.

  1. 1Input: " hello world " (2 leading spaces, 1 between, 2 trailing)
  2. 2split() → ["hello", "world"] (all spaces consumed, no empty strings)
  3. 3reverse → ["world", "hello"]
  4. 4join → "world hello" (single space, no leading/trailing)
  5. 5In-place: reverse all → " dlrow olleh "
  6. 6In-place: reverse each word → " world hello "
  7. 7In-place: compact spaces → "world hello"

Code Walkthrough: Python and Java

Python one-liner: def reverseWords(s: str) -> str: return " ".join(s.split()[::-1]). That is the complete solution — 46 characters. If the interviewer requires explicit steps: words = s.split(); words.reverse(); return " ".join(words). Both are O(n) time and O(n) space.

Java split-reverse-join: public String reverseWords(String s) { String[] words = s.trim().split("\\s+"); StringBuilder sb = new StringBuilder(); for (int i = words.length - 1; i >= 0; i--) { if (sb.length() > 0) sb.append(" "); sb.append(words[i]); } return sb.toString(); }. Uses trim() + "\\s+" regex to handle all space edge cases; StringBuilder for O(n) concatenation.

Java in-place (O(1) space): convert to char array; reverse entire array; scan to find word boundaries and reverse each word in-place; make a second pass to compact spaces (write non-space chars and single separators from front). This is ~30 lines in Java and is the version to use when the interviewer explicitly asks for O(1) space. Time remains O(n).

⚠️

Java: Use split("\\s+") Not split(" ")

In Java, String.split(" ") splits on a single literal space and produces empty strings wherever two or more consecutive spaces appear. Use split("\\s+") instead — the regex matches one or more whitespace characters as a single delimiter. Also call trim() first to remove leading and trailing spaces, otherwise split("\\s+") can still produce an empty string at the start if the input begins with whitespace.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now