Reverse Words in a String II - Problem

You're given a character array representing a sentence, and your task is to reverse the order of the words while keeping each word intact.

For example, if you have the sentence "the sky is blue", you need to transform it to "blue is sky the".

Key constraints:

  • A word is defined as a sequence of non-space characters
  • Words are separated by exactly one space
  • You must solve this in-place without allocating extra space
  • The input is guaranteed to not have leading or trailing spaces

This problem tests your ability to manipulate strings efficiently using two-pointers technique and understanding of in-place array operations.

Input & Output

example_1.py โ€” Basic Word Reversal
$ 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 reversed in order: 'the sky is blue' becomes 'blue is sky the', but each individual word maintains its internal character order.
example_2.py โ€” Two Words
$ Input: s = ['a',' ','g','o','o','d',' ','e','x','a','m','p','l','e']
โ€บ Output: ['e','x','a','m','p','l','e',' ','g','o','o','d',' ','a']
๐Ÿ’ก Note: Three words 'a good example' become 'example good a'. Notice how single characters and longer words are handled the same way.
example_3.py โ€” Single Word
$ Input: s = ['h','e','l','l','o']
โ€บ Output: ['h','e','l','l','o']
๐Ÿ’ก Note: With only one word and no spaces, the array remains unchanged since there's only one word to reverse the order of.

Constraints

  • 1 โ‰ค s.length โ‰ค 104
  • s[i] is an English letter (lowercase or uppercase) or 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
The Magic of Two-Step ReversalStep 1: Original Array"the""sky""is""blue"Step 2: Reverse Entire Array"eulb""si""yks""eht"Step 3: Reverse Each Word"blue""is""sky""the"๐ŸŽฏ Key InsightTwo reversals = Words in reverse order!Time: O(n) | Space: O(1) | Perfect for in-place requirement
Understanding the Visualization
1
Initial State
We have words in original order: 'the sky is blue'
2
Reverse Everything
Flip the entire array: 'eulb si yks eht'
3
Fix Each Word
Reverse each word individually: 'blue is sky the'
4
Mission Accomplished
Words are now in reverse order, each properly oriented!
Key Takeaway
๐ŸŽฏ Key Insight: The magic happens because reversing twice (entire array, then each word) efficiently achieves word-order reversal while maintaining each word's integrity - all in O(n) time with O(1) space!
Asked in
Google 15 Amazon 12 Microsoft 10 Meta 8
42.0K Views
Medium Frequency
~15 min Avg. Time
1.9K 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