Reverse Words in a String II
The 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: s = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Step 1: Reverse the entire array
- Original:
- ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
- After reversing:
- ["e","u","l","b"," ","s","i"," ","y","k","s"," ","e","h","t"]
Step 2: Reverse each word individually
- Reverse "eulb" → "blue"
- Reverse "si" → "is"
- Reverse "yks" → "sky"
- Reverse "eht" → "the" Final Output: s = ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
Input: s = ["a"] Output: ["a"] Explanation: Since there is only one character (one word), no changes are needed.
Input : s = ["c","o","d","e"," ","i","s"," ","f","u","n"]
- 1 <= s.length <= 105
- s[i] is an English letter (uppercase or lowercase), digit, or space ' '.
- There is at least one word in s.
- s does not contain leading or trailing spaces.
- All the words in s are guaranteed to be separated by a single space.
cpp
class Solution {
public:
void reverseWords(vector<char>& s) {
// Your code goes here
}
};java
class Solution {
public void reverseWords(char[] s) {
// Your code goes here
}
}python
class Solution(object):
def reverseWords(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
# Your code goes herejavascript
/**
* @param {character[]} s
* @return {void} Do not return anything, modify s in-place instead.
*/
var reverseWords = function(s) {
// Your code goes here
};csharp
public class Solution
{
public void ReverseWords(char[] s)
{
// Your code goes here
}
}go
func reverseWords(s []byte) {
//your code goes here
}Stuck? Show a way to structure it+
- 01Clarify whether words are separated by single spaces.
- 02Reverse the full character array.
- 03Scan each word boundary.
- 04Reverse every word segment.
- 05Return the transformed array or string.
Reference answer
Then expect these follow-ups
How would you normalize multiple spaces in place?
Tests: complexity analysis
What differs for immutable strings?
Tests: follow-up reasoning
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question