Reverse Words in a String II Problem
Description
LeetCode Problem 186.
Given a character array s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by a single space.
Your code must solve the problem in-place, i.e. without allocating extra space.
Example 1:
Input: s = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
Example 2:
Input: s = ["a"]
Output: ["a"]
Constraints:
1 <= s.length <= 10^5s[i]is an English letter (uppercase or lowercase), digit, or space' '.- There is at least one word in
s. sdoes not contain leading or trailing spaces.- All the words in
sare guaranteed to be separated by a single space.
Solution
Approach: Reverse Each Word, Then Everything
Reversing the whole array puts the words in the right order, but each word comes out spelled backwards. Reversing each word on its own fixes the spelling. Doing both, in either order, gives the answer, and both are in-place swaps.
For example, with "the sky":
- reverse each word:
"eht yks" - reverse the whole array:
"sky the"
To find the words, scan the array with an index j and remember where the current word started. When s[j] is a space, or j has reached the end of the array, the word is s[start..j-1]: reverse it and set start = j + 1. Treating the end of the array like a space is what makes the last word get reversed too. Then reverse the whole array.
Since the problem guarantees single spaces and no leading or trailing ones, the spaces never need to move on their own.
Complexity: O(n) time, as every character is swapped at most twice. O(1) extra space.
class Solution:
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
def reverse(i: int, j: int) -> None:
while i < j:
s[i], s[j] = s[j], s[i]
i, j = i + 1, j - 1
# Reverse each word, then the whole array: the words swap places and read forwards again.
start = 0
for j in range(len(s) + 1):
if j == len(s) or s[j] == " ":
reverse(start, j - 1)
start = j + 1
reverse(0, len(s) - 1)