Reverse words in a sentence
Given 'I love Python', return 'Python love I'.
This shows up a lot in screening rounds for freshers, usually as a warm-up. The catch isn't the reversing, it's the spacing.
Try your function on these before you call it done:
| Input | Expected |
|---|---|
'I love Python' |
'Python love I' |
' hello world ' |
'world hello' |
'single' |
'single' |
'' |
'' |
The second one is where most first attempts go wrong. If you split on a single space with split(' '), you get empty strings in the list and the output ends up with odd gaps.
Starter code
def reverse_words(s: str) -> str:
pass
💡 Hint 1
split() then reverse
✅ Show solution
def reverse_words(s):
return ' '.join(s.split()[::-1])
How it works
s.split() with no argument splits on any run of whitespace and throws away leading and trailing spaces. That one detail handles the messy-spacing test case for free. [::-1] reverses the list, and ' '.join(...) glues the words back together with exactly one space.
If they say "no built-ins"
Some interviewers want to see you do it by hand:
def reverse_words(s):
words, current = [], ""
for ch in s:
if ch == " ":
if current:
words.append(current)
current = ""
else:
current += ch
if current:
words.append(current)
out = ""
for w in reversed(words):
out += w + " "
return out.strip()
It's longer but it shows you understand what split() is doing for you.
Complexity: O(n) time and O(n) space, where n is the length of the string.
A follow-up they like: "reverse the letters inside each word but keep the word order". That's ' '.join(w[::-1] for w in s.split()).
Tip: run your code in a local Python environment, Jupyter or Google Colab.