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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code