Module 4 · Smart Patterns for Lists · Lesson 10 of 40
Two pointers
Walk two positions through a list at once, from both ends or at two speeds, to turn O(n²) into O(n).
In this lesson · about 22 minutes
- Use left and right pointers on a sorted list
- Use slow and fast pointers to remove duplicates in place
- Recognise problems where two pointers fit
A pointer here just means a variable that holds an index, like left = 0. The two pointer pattern uses two of them at once and moves them cleverly, so you never need a loop inside a loop.
Type 1: from both ends
Start left at the beginning and right at the end. Look at the two items, decide something, then move one pointer inward. Stop when they meet. Each step moves a pointer, so there are at most n steps: O(n).
Example: in a sorted list, find two numbers that add up to a target. If the sum is too small, move left right (to a bigger number). If it is too big, move right left (to a smaller number).
Try it · see it work
Two pointers: find a pair with a target sum
Press Next step and read why each pointer moves. Then try a target like 30 that has no answer.
Step 1 of 41 + 15 = 16, too small. Move left one step right to get a bigger number.
Type 2: same direction (slow and fast)
Both pointers start on the left. The fast pointer reads every item. The slow pointer marks where the next "good" item should be written. This lets you clean up a list in place, with O(1) extra space.
Example: a sorted list has repeats, like [1, 1, 2, 3, 3]. Keep one copy of each. Fast walks every item; whenever it finds a new value, write it at slow and move slow forward.
slow = 1
for fast in range(1, len(nums)):
if nums[fast] != nums[slow - 1]:
nums[slow] = nums[fast]
slow += 1
# the first 'slow' items are now unique
When to think "two pointers"
- The list is sorted, and you look for a pair.
- You need to compare things from both ends (palindromes, reversing).
- You must change the list in place without extra memory.
- You want to split items into groups (like all zeros first) in one pass.
Exercise
Pair with a target sum
nums is sorted. Write pair_sum(nums, target) that returns the pair of indexes [left, right] whose numbers add to the target, or None if there is no pair. Use two pointers from both ends.
Exercise
Remove duplicates in place
nums is sorted. Write remove_dupes(nums) that moves one copy of each value to the front of the same list and returns how many unique values there are. For [1, 1, 2, 3, 3] return 3, and the list should start [1, 2, 3, ...].
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.