#151
Reverse Words in a String
MediumTwo PointersStringTwo PointersString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a two-pointer technique to reverse the words in place while managing spaces. This reduces the number of passes over the string and avoids extra space for storing words.
⚙️
Algorithm
4 steps- 1Step 1: Trim the input string to remove leading and trailing spaces.
- 2Step 2: Use two pointers to find the start and end of each word, and reverse the characters in place.
- 3Step 3: Reverse the entire string to get the words in the correct order.
- 4Step 4: Clean up spaces by collapsing multiple spaces into a single space.
solution.py16 lines
1# Full working Python code
2def reverseWords(s):
3 s = s.strip()
4 words = list(s)
5 n = len(words)
6 start = 0
7 for end in range(n):
8 if words[end] == ' ':
9 if start != end:
10 words[start:end] = reversed(words[start:end])
11 start = end + 1
12 words[start:] = reversed(words[start:])
13 return ''.join(words).replace(' ', ' ')
14
15result = reverseWords(' hello world ')
16print(result)ℹ
Complexity note: The time complexity is O(n) because we only traverse the string a few times. The space complexity is O(1) since we are modifying the string in place without using extra space for another array.
- 1Understanding how to manage spaces is crucial.
- 2In-place modifications can save memory and improve efficiency.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.