Reverse Words in a String II - Problem
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.
Input & Output
Example 1 — Basic Case
$
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"]
💡 Note:
The words are "the", "sky", "is", "blue". Reversing their order gives "blue", "is", "sky", "the".
Example 2 — Single Word
$
Input:
s = ["a"]
›
Output:
["a"]
💡 Note:
Only one word, so it remains the same after reversal.
Example 3 — Two Words
$
Input:
s = ["h","i"," ","b","y","e"]
›
Output:
["b","y","e"," ","h","i"]
💡 Note:
Two words: "hi" and "bye". After reversal: "bye hi".
Constraints
- 1 ≤ s.length ≤ 104
- s[i] is either a lowercase English letter or a space ' '
- There is at least one word in s
- s does not contain leading or trailing spaces
- All words are separated by exactly one space
Visualization
Tap to expand
Understanding the Visualization
1
Input
Character array representing sentence with words separated by spaces
2
Process
Reverse word order while keeping individual words readable
3
Output
Same array with words in reversed order
Key Takeaway
🎯 Key Insight: Two reversals (entire array, then each word) achieve in-place word reordering
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code