Reverse Words in a String III - Problem
Word Reversal Challenge: Given a string s containing multiple words separated by spaces, your task is to reverse the characters within each individual word while keeping the words in their original positions and preserving all whitespace.

Think of it as flipping each word like a pancake - the word order stays the same, but each word gets flipped individually. For example, "Hello World" becomes "olleH dlroW".

Goal: Transform each word by reversing its character order
Input: A string with words separated by single spaces
Output: The same string with each word's characters reversed

Input & Output

example_1.py โ€” Basic word reversal
$ Input: s = "Let's take LeetCode contest"
โ€บ Output: "s'teL ekat edoCteeL tsetnoc"
๐Ÿ’ก Note: Each word is reversed individually: 'Let's' becomes 's'teL', 'take' becomes 'ekat', 'LeetCode' becomes 'edoCteeL', and 'contest' becomes 'tsetnoc'. The spaces between words are preserved.
example_2.py โ€” Single word
$ Input: s = "God"
โ€บ Output: "doG"
๐Ÿ’ก Note: With only one word, we simply reverse its characters: 'G' and 'd' swap positions while 'o' stays in the middle, resulting in 'doG'.
example_3.py โ€” Mixed length words
$ Input: s = "I love programming"
โ€บ Output: "I evol gnimmargor"
๐Ÿ’ก Note: Single character 'I' remains unchanged, 'love' becomes 'evol', and 'programming' becomes 'gnimmargor'. Each word boundary is preserved by the spaces.

Constraints

  • 1 โ‰ค s.length โ‰ค 5 ร— 104
  • s contains printable ASCII characters
  • s does not contain any leading or trailing spaces
  • There is at least one word in s
  • All the words in s are separated by a single space

Visualization

Tap to expand
๐Ÿฅž The Pancake Flipping TechniqueStep 1: Original pancake stacks (words)LBottometsTopPlate 1takePlate 2Step 2: After flipping with two spatulassBottomteLTops'teLekatekat๐Ÿฅ„ Two Spatulas Technique1. Left spatula starts at bottom pancake2. Right spatula starts at top pancake3. Swap pancakes, move spatulas inward4. Stop when spatulas meet in middle
Understanding the Visualization
1
Identify the Stack
Find where each word (pancake stack) begins and ends
2
Position Spatulas
Place left spatula at bottom pancake, right spatula at top pancake
3
Flip Process
Swap pancakes at spatula positions and move spatulas toward center
4
Stack Complete
When spatulas meet, the stack is perfectly flipped - move to next plate
Key Takeaway
๐ŸŽฏ Key Insight: The two-pointer technique transforms an O(nยฒ) string manipulation problem into an elegant O(n) solution by working directly with the character array, avoiding expensive string operations and temporary objects.
Asked in
Amazon 15 Microsoft 12 Google 8 Apple 6
85.0K Views
Medium Frequency
~15 min Avg. Time
3.2K 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