557 - Reverse Words in a String III
Difficulty: Easy | Pattern: String Manipulation | Company tags: Amazon, Microsoft, Google
Problem Statement
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetno c"
Example 2:
Input: s = "Mr Ding"
Output: "rM gniD"
Solution
def reverseWords(s: str) -> str:
return ' '.join(word[::-1] for word in s.split())
Algorithm Flow
One-Liner Breakdown
s.split()→ splits on whitespace (handles multiple spaces)word[::-1]→ reverses each word using Python slice' '.join(...)→ rejoins with single space
In-Place Approach (for interviews)
def reverseWords(s: str) -> str:
result = list(s)
start = 0
for end in range(len(result) + 1):
if end == len(result) or result[end] == ' ':
# Reverse the word [start, end)
l, r = start, end - 1
while l < r:
result[l], result[r] = result[r], result[l]
l += 1
r -= 1
start = end + 1
return ''.join(result)
Dry Run
s = "Let's take"
In-place:
- end=5 (space): reverse "Let's" → "s'teL"
- end=10 (end): reverse "take" → "ekat"
Result: "s'teL ekat" ✓
Edge Cases
- Single word → just reverse it
- Multiple spaces →
split()collapses them; in-place approach must handlestart > end - Empty string → return
""
Complexity
- Time: O(n)
- Space: O(n) for one-liner (split creates list); O(1) extra for in-place
Key Terms
| Term | Definition |
|---|---|
| Two pointers | l and r start at opposite ends of a word and move toward each other, swapping characters until they meet. |
| In-place reversal | Modifying the character array directly (via a mutable list(s)) instead of allocating new strings, giving O(1) extra space. |
| Tokenization | Splitting a string into words on a delimiter (here, whitespace) so each token can be processed independently. |
| Word boundary | The index range [start, end) marking where a single word begins and ends, detected by scanning for spaces or the end of string. |
FAQ
Q: Why does the in-place approach use result[end] == ' ' as the stopping condition instead of just splitting on spaces?
A: Scanning manually avoids creating intermediate substrings, so the reversal can be done directly on a mutable character list in O(1) extra space, which is what interviewers expect beyond the one-liner.
Q: Does this problem require handling multiple consecutive spaces?
A: LeetCode's constraints guarantee no leading/trailing spaces and no double spaces, but it's worth mentioning to the interviewer that the in-place solution naturally tolerates it since start > end for an empty token is a no-op swap loop.
Q: How is this different from LeetCode 151 (Reverse Words in a String)? A: 151 reverses the order of the words themselves (and strips extra spaces), while 557 reverses the characters within each word but keeps word order and spacing intact.
Q: What's the time and space complexity, and why does it matter here?
A: O(n) time since every character is visited a constant number of times; the one-liner is O(n) space due to split() and join(), while the manual two-pointer version is O(1) extra space (excluding the output string), which is the stronger answer for a follow-up.
Q: Can recursion or a stack be used instead of two pointers? A: Yes, but it adds O(k) space for a word of length k with no benefit — two pointers is the canonical, space-optimal way to reverse a fixed-size segment in place.
Quick Revision
- Goal: reverse characters inside each word, keep word order and whitespace unchanged.
- One-liner:
' '.join(w[::-1] for w in s.split())— simple but O(n) extra space. - Interview-grade approach: scan for word boundaries, reverse each word in place with two pointers.
- Two pointers:
lat word start,rat word end, swap and move inward whilel < r. - Word boundary detection: a space or end-of-string marks the end of the current word.
- Dry run "Let's take" → reverse "Let's" to "s'teL", reverse "take" to "ekat" → "s'teL ekat".
- Edge cases: single word, empty string, string ending exactly at a word (check
end == len(result)). - Time: O(n); Space: O(n) for split/join, O(1) extra for in-place swapping.
- Pattern reused in: reversing substrings, palindrome checks, and in-place array reversal problems.
Related Problems
- Reverse Words in a String (LeetCode 151) — reverses word order, not characters within words; same tokenization idea, opposite target (name only, not in this directory).
- Reverse String (LeetCode 344) — the same two-pointer in-place reversal applied to an entire string rather than per-word segments (name only, not in this directory).
- 206 - Reverse Linked List — different data structure, but the same "reverse in place while preserving surrounding structure" mental model.