151. Reverse Words in a String
- Pattern:
- string split / two pointers
- Time:
- O(n)
- Space:
- O(n)
- Written:
Problem
s, reverse the order of the words (not characters). Words are separated by spaces; input may contain leading/trailing/multiple spaces which must be collapsed into single spaces in the output.
" the sky is blue " → output "blue is sky the".
Approach
trim()the input to remove leading/trailing whitespace.Use two pointers ( first,second) to scan and extract each word: skip spaces by advancingfirst; advancesecondfromfirstuntil a space or end of string is hit; extract the word vias.substring(first, second).Store words in a List<String>(size unknown up front → can't use a fixed-size array).Collections.reverse(words)to reverse word order (not characters).String.join(" ", words)to rebuild the final string.
Solution
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Solution {
public String reverseWords(String s) {
s = s.trim();
List<String> words = new ArrayList<>();
int first = 0;
while (first < s.length()) {
if (s.charAt(first) == ' ') {
first++;
continue;
}
int second = first;
while (second < s.length() && s.charAt(second) != ' ') {
second++;
}
words.add(s.substring(first, second));
first = second;
}
Collections.reverse(words);
return String.join(" ", words);
}
}Takeaways
OCA concepts reinforced (chapter 3)
String immutability — why looping +=on Strings is wasteful;StringBuilder/List+String.join()avoid the string pool churn.substring(begin, end)— end index is exclusive. Classic exam trap.Array vs. ArrayList— arrays need a fixed size declared up front; useArrayList/Listwhen the size is unknown (word count here).Generics / diamond operator — List<String> words = new ArrayList<>();avoids raw-type warnings and unchecked-conversion issues.Collections.reverse()— ajava.util.Collectionshelper, same family asCollections.sort().
Java 8
String.join() (Java 8), diamond operator (Java 7+).
Complexity
Time: O(n) — each character visited a constant number of times. Space: O(n) — for the word list and rebuilt string.
Re-quiz
Can I write it from memory without looking? Can I do it in place on a char[](reverse the whole string, then each word) with O(1) extra space?