459. Reverse Words in a String II

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"]

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"]

Example 2:

Input: s = ["a"]

Output: ["a"]

Explanation:

Since there is only one character (one word), no changes are needed.

Now Your Turn!

Pick the correct output for the given input

Input : s = ["c","o","d","e"," ","i","s"," ","f","u","n"]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 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.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
void reverseWords(vector<char>& s) {
// Your code goes here
}
};
Test Case

Input:

S