This problem requires reversing the order of words in a character array in-place, meaning without using extra space proportional to the input size. The solution leverages the power of in-place reversal using two-pointers technique.
Approach:
The core idea is to perform three steps of reversal:
Reverse each word individually: Iterate through the array. When a space is encountered, it marks the end of a word. Reverse the characters within that word's boundaries using a helper function.
Reverse the entire array: After reversing individual words, the words are in the correct order within the array, but the order of words themselves is reversed. To fix this, reverse the entire array.
Return: The modified array s
now contains words in reversed order.
Time Complexity Analysis:
Therefore, the overall time complexity is O(n), which is linear with respect to the input size.
Space Complexity Analysis:
The algorithm performs all operations in-place. The only extra space used is for the function call stack and a few temporary variables for swapping characters, which is considered constant space. Therefore, the space complexity is O(1), which is constant.
Code Implementation and Explanation (Python):
class Solution:
def reverseWords(self, s: List[str]) -> None:
def reverse(i: int, j: int): # Helper function to reverse a portion of the array
while i < j:
s[i], s[j] = s[j], s[i]
i, j = i + 1, j - 1
n = len(s)
i = 0 # Start index of current word
for j in range(n): # Iterate through the array
if s[j] == " ": # Space signifies end of a word
reverse(i, j - 1) # Reverse the current word
i = j + 1 # Move the start index to the next word
elif j == n - 1: # Last word
reverse(i, j) # Reverse the last word
reverse(0, n - 1) # Reverse the entire array to get the final order of words
The other languages (Java, C++, Go, TypeScript) follow the same logic and algorithmic steps, differing only in syntax and data structure handling. Their time and space complexities remain consistent. The helper function reverse
is crucial for the efficient in-place reversal of sections of the array.