Challenge: Reverse in Place
Completed
Read a list of words and reverse it in place using two positions that move towards each other and swap (no reverse(), no slicing, no new list). Print the words separated by spaces.
Input
One line of words.
Output
The words in reverse order.
Example
Input
one two three four
Output
four three two one
Editor
Python
Hints
Start left at 0 and right at the last index.
Swap, then move left forward and right backward, until they meet.
Solution explanation
About n/2 swaps: O(n) time, and only two extra variables: O(1) space.
Show solution
words = input().split()
left, right = 0, len(words) - 1
while left < right:
words[left], words[right] = words[right], words[left]
left += 1
right -= 1
print(" ".join(words)) Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module