186. Reverse Words in a String II
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The core of this problem is to reverse the order of words within a character array. The critical constraints are that this must be done in-place (without allocating extra space proportional to the input size) and that words are separated by a single space, with no leading or trailing spaces.
Solution
Reverse Words in a String II in Python
class Solution:
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
n = len(s)
# Helper function to reverse a portion of the list.
def reverse(left, right):
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
# Step 1: Reverse the entire list of characters.
# This puts the words in the correct order, but each word is reversed.
# e.g., "the sky is blue" -> "eulb si yks eht"
reverse(0, n - 1)
start = 0
# Step 2: Reverse each word individually.
for i in range(n + 1):
# Find the end of a word (either a space or end of the list).
if i == n or s[i] == ' ':
# The word is from index `start` to `i-1`.
reverse(start, i - 1)
# Update the start of the next word.
start = i + 1
Reverse Words in a String II in Java
class Solution {
public void reverseWords(char[] s) {
// Step 1: Reverse the entire character array.
// This puts the words in the correct order, but each word is reversed.
// e.g., "the sky is blue" -> "eulb si yks eht"
reverse(s, 0, s.length - 1);
int start = 0;
// Step 2: Reverse each word individually.
for (int i = 0; i <= s.length; i++) {
// Find the end of a word (either a space or end of the array).
if (i == s.length || s[i] == ' ') {
// The word is from index `start` to `i-1`.
reverse(s, start, i - 1);
// Update the start of the next word.
start = i + 1;
}
}
}
// Helper function to reverse a part of the char array in-place.
private void reverse(char[] s, int left, int right) {
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
Reverse Words in a String II in C++
class Solution {
public:
void reverseWords(vector<char>& s) {
// Step 1: Reverse the entire character array.
// This puts the words in the correct order, but each word is reversed.
// e.g., "the sky is blue" -> "eulb si yks eht"
reverse(s.begin(), s.end());
int n = s.size();
int start = 0;
// Step 2: Reverse each word individually.
for (int i = 0; i <= n; ++i) {
// Find the end of a word (either a space or end of the array).
if (i == n || s[i] == ' ') {
// The word is from index `start` to `i-1`.
reverse(s.begin() + start, s.begin() + i);
// Update the start of the next word.
start = i + 1;
}
}
}
};
Reverse Words in a String II in TypeScript
/**
Do not return anything, modify s in-place instead.
*/
function reverseWords(s: string[]): void {
const n = s.length;
// Helper function to reverse a portion of the array.
const reverse = (left: number, right: number) => {
while (left < right) {
[s[left], s[right]] = [s[right], s[left]];
left++;
right--;
}
};
// Step 1: Reverse the entire array.
// This puts the words in the correct order, but each word is reversed.
// e.g., "the sky is blue" -> "eulb si yks eht"
reverse(0, n - 1);
let start = 0;
// Step 2: Reverse each word individually.
for (let i = 0; i <= n; i++) {
// Find the end of a word (either a space or end of the array).
if (i === n || s[i] === ' ') {
// The word is from index `start` to `i-1`.
reverse(start, i - 1);
// Update the start of the next word.
start = i + 1;
}
}
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.