#557
Reverse Words in a String III
EasyTwo PointersStringTwo PointersString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a two-pointer technique to reverse the words in place. This is efficient because it only requires a single pass through the string and uses minimal extra space.
⚙️
Algorithm
3 steps- 1Step 1: Convert the string to a character array for in-place modification.
- 2Step 2: Use two pointers to identify the start and end of each word, and reverse the characters in that range.
- 3Step 3: Continue until all words are reversed, then return the modified character array as a string.
solution.py12 lines
1# Full working Python code
2s = "Let's take LeetCode contest"
3char_list = list(s)
4start = 0
5for end in range(len(char_list)):
6 if char_list[end] == ' ' or end == len(char_list) - 1:
7 if end == len(char_list) - 1:
8 end += 1
9 char_list[start:end] = char_list[start:end][::-1]
10 start = end + 1
11result = ''.join(char_list)
12print(result)ℹ
Complexity note: The time complexity is O(n) because we traverse the string a single time to reverse the words. The space complexity is O(n) due to the character array used for in-place modification.
- 1Reversing words can be efficiently done using in-place techniques.
- 2Understanding string manipulation and character arrays is crucial for optimal solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.