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
Reverse Words in a String II INPUT Character Array s[] t h e s k y i s b l u e Words Identified: "the" "sky" "is" "blue" Constraint: In-place only! O(1) extra space Array length: 15 ALGORITHM STEPS 1 Reverse Entire Array "the sky is blue" --> "eulb si yks eht" 2 Find Word Boundaries Scan for spaces to find start/end of each word 3 Reverse Each Word "eulb" --> "blue" "si" --> "is", etc. 4 Two-Pointer Swap Use left/right pointers to swap in-place Reverse Helper Function: while(L < R): swap(s[L], s[R]) L++, R-- FINAL RESULT Reversed Word Order: b l u e i s s k y t h e Result String: "blue" "is" "sky" "the" Complexity: Time: O(n) - two passes Space: O(1) - in-place OK Key Insight: The two-step reverse technique is a classic in-place transformation pattern: 1) Reverse the entire array to get words in correct order (but each word is backwards) 2) Reverse each individual word to restore correct spelling. This achieves O(1) space! TutorialsPoint - Reverse Words in a String II | Optimal Two-Pass Reverse Approach
Asked in
Microsoft 35 Amazon 28 Google 22 Facebook 18
32.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen