MediumNeetCode150Two PointersString
Reverse Words in a String
Reverse order of words.
Examples
Input
s = "the sky is blue"
Output
blue is sky the
Reversed word order.
Constraints
- •
1 <= s.length <= 10^4 - •
s has at least one word - •
No leading/trailing spaces in result
Approaches
Split, reverse, join.
CodeT: O(n) | S: O(n) array
Reverse all chars then each word.
CodeT: O(n) | S: O(1) in-place (list)
Same approach.
CodeT: O(n) | S: O(n)
Complexity Comparison
| Approach | Time | Space | Description |
|---|---|---|---|
| Split and Reverse | O(n) | O(n) array | Split, reverse, join. |
| Two Pointer Reverse | O(n) | O(1) in-place (list) | Reverse all chars then each word. |
| Split Reverse Optimized | O(n) | O(n) | Same approach. |
Split and Reverse
T: O(n)S: O(n) array
Split, reverse, join.
Two Pointer Reverse
T: O(n)S: O(1) in-place (list)
Reverse all chars then each word.
Split Reverse Optimized
T: O(n)S: O(n)
Same approach.
Common Mistakes
Not handling multiple spaces
Extra spaces in output
Off-by-one