Reverse Words in a String
Problem
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."the sky is blue"Output"blue is sky the"" hello world "Output"world hello""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
class Solution {
public String reverseWords(String s) {
}
}
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)
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.
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.
BetterManual Scan + Deque
O(n)Space O(n)Trim with two pointers, then scan left to right building one word at a time.
When a word ends, push it to the front of a deque; the deque therefore holds
the words already reversed, ready for String.join.
public String reverseWords(String s) { int left = 0, right = s.length() - 1; while (left <= right && s.charAt(left) == ' ') left++; while (left <= right && s.charAt(right) == ' ') right--; Deque<String> d = new ArrayDeque<>(); StringBuilder word = new StringBuilder(); while (left <= right) { char c = s.charAt(left); if (c == ' ' && word.length() != 0) { d.offerFirst(word.toString()); // word finished word.setLength(0); } else if (c != ' ') { word.append(c); } left++; } d.offerFirst(word.toString()); // last word return String.join(" ", d); }
No regex and explicit parsing, but still stores every word separately.
OptimalReverse All, Reverse Each Word, Compact
O(n)Space O(n)*Work on a char[]: reverse it fully, then reverse each
space-delimited word back. Finally a read/write pointer pass copies words left and
writes a single space between them. *Java strings are immutable, so the
char[] costs O(n); beyond that buffer the extra space is O(1).
public String reverseWords(String s) { char[] str = s.toCharArray(); reverse(str, 0, str.length - 1); int start = 0; for (int end = 0; end <= str.length; end++) { if (end == str.length || str[end] == ' ') { reverse(str, start, end - 1); // flip each word back start = end + 1; } } return cleanSpaces(str); } private void reverse(char[] a, int l, int r) { while (l < r) { char t = a[l]; a[l++] = a[r]; a[r--] = t; } } private String cleanSpaces(char[] a) { int i = 0, j = 0, n = a.length; while (j < n) { while (j < n && a[j] == ' ') j++; // skip spaces while (j < n && a[j] != ' ') a[i++] = a[j++]; // copy word while (j < n && a[j] == ' ') j++; if (j < n) a[i++] = ' '; // one gap } return new String(a, 0, i); }
Dry run" hi yo"
- starthiyooriginal
- rev alloyihwords in order
- word 1ysoeihreverse [0,1]
- word 2yohsiereverse [3,4]
- cleanyohi·"yo hi" ✔
Constant auxiliary space on a mutable buffer — the follow-up answer.
At a glance
| Level | Approach | Time | Space |
|---|---|---|---|
| Brute Force | Split & Join (Built-ins) | O(n) | O(n) |
| Better | Manual Scan + Deque | O(n) | O(n) |
| Optimal | Reverse All, Reverse Each Word, Compact | O(n) | O(n)* |
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.
- Ask whether built-ins like
splitare 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.