AI Hints
Home›DSA in Python Tutorial›Array Practice
DSA in Python · Lesson 16 of 132

Practice: Reverse in Place

No extra list.

⏱ 2 min read▶ Video at 18:23🎓 Free
Watch this lesson in the DSA in Python courseWatch on YouTube ↗Full DSA in Python course

Here's your first practice problem. Reverse a list, without creating a second list, and without using the built in reverse. Pause the video, and think about how two pointers could help.

Practice: Reverse in Place
From the video: Practice: Reverse in Place
  • Reverse a list
  • No second list
  • Pause and think

Swapping from the ends

Put one pointer at each end. Swap the two items, then move both pointers towards the middle. Stop when they meet. Python can swap two values in one line, with a comma. Run it. The list is reversed, using O of one extra space, and O of N time.

reverse.pypython
def reverse(items):
    left, right = 0, len(items) - 1
    while left < right:
        items[left], items[right] = items[right], items[left]
        left += 1
        right -= 1

letters = ["a", "b", "c", "d", "e"]
reverse(letters)
print(letters)
Output
['e', 'd', 'c', 'b', 'a']

Built in versions

In real code, you'd usually just call the built in tools. List dot reverse reverses in place. Slicing with a step of minus one makes a reversed copy. And reversed gives you the items backwards, one at a time. But interviewers love asking you to write it yourself, to see how you think.

keyvalue
a.reverse()in place, O(1) space
a[::-1]a reversed copy
reversed(a)items backwards
Write it yourselfinterview favourite

Summary

Swap from both ends, and move inwards. That reverses a list in place, in O of N time and O of one space. Next, checking palindromes.

Key takeaways
  • Swap the ends
  • Move inwards
  • O(1) extra space
Next up: Practice: Palindromes — reads the same both ways