Link: 151. Reverse Words in a String-Medium
Track: Amazon Tag
Question
Restate the problem
- Given a string
- The word order is revered
- Words are separated by exactly one space
- The result has np leading or trailing spaces
Edge Case
- single word:
"word"→"word" - Only spaces:
" "→""
Method 1 - Pythonic Split + Join
Method 2 - O(1)
Method 1 - Pythonic Split + Join
Approach
words = s.split()→ list of words without empty tokens- Reverse
words - Return
" ".join(reversed_words)
Complexity
- Time Complexity: O(n)
- Space Complexity: O(n)
Code
class Solution:
def reverseWords(self, s: str) -> str:
words = s.split()
words.reverse()
res = " ".join(words)
return resHistory
- Feb-15-2026 Peeked