progress

~/problems / Two pointers

Reverse a list in place

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Write reverse_in_place(nums: list[int]) -> None that reverses nums in place: change the list you were given, without building a new one, and return nothing.

nums = [1, 2, 3, 4, 5]
reverse_in_place(nums)
nums   # [5, 4, 3, 2, 1]

nums = [7, 8]
reverse_in_place(nums)
nums   # [8, 7]
  • 0 <= len(nums) <= 10^5.
  • Use O(1) extra space: no second list, no slicing, and no reversed() or list.reverse(). The point is to write the loop.
Show hint

put lo on the first index and hi on the last. Swap the two values, step both pointers one place inwards, and stop when they meet.

Topic: Two pointers. Sorted input + moving ends inward; skip duplicates; pairs and triples.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc