Intuition
Use sliding window to append words from the end to beginning in correct order
- initialize res and right pointer
- start from back and find end of the word using while r greater than equal to 0 and s[r] == ' '
- when beginning of word is found initialize l pointer by using while s[l] != " "
- append to result array window between l and r
- move right pointer to l which is the beginning of the word
- Repeat
Optimal Solution
class Solution:
def reverseWords(self, s: str) -> str:
res = []
s = s.strip()
while r >= 0:
# skip spaces
while r >= 0 and s[r] == ' ':
r -= 1
# find beginning of the word
l = r
while l >= 0 and s[l] != ' ':
l -=1
# extract the word and add to result
if r >= 0:
res.append(s[l + 1 : r + 1])
# move the right pointer to the left pointer
r = l
return " ".join(res)
Time Complexity
Time Complexity = O(N)
Space Complexity = O(N)