Module 2 ยท Arrays, strings and hashing Lesson 5 of 15
Two pointers
Two positions moving through one sequence, usually from both ends or at different speeds. It turns a nested loop into a single pass.
The concept
Two pointers is one loop with two moving positions instead of two nested loops. Starting at both ends is for a sorted array and a target sum: if the sum is too small, move the left pointer up; too big, move the right one down. Running one behind the other is for removing duplicates in place or reversing part of a sequence.
The reason it works is that each pointer only moves forward, so the whole thing is one pass โ O(n) time and no extra memory. The trick to explaining it is the invariant: "everything to the left of the slow pointer is processed, and the fast one is looking for the next item to keep".
def two_sum_sorted(nums, target):
left, right = 0, len(nums) - 1
while left < right:
s = nums[left] + nums[right]
if s == target: return [left, right]
if s < target: left += 1 # need bigger -> move left up
else: right -= 1 # need smaller -> move right down
return []
# Sorted input required. One pass: O(n) time, O(1) extra space.Common mistakes
The mistakes are forgetting the pointers may cross โ the loop condition is usually while (left < right) โ and trying to use the two-ended version on an unsorted array, where moving a pointer tells you nothing. Sort first if the question allows it, and say that you did.
Worked example
Sorted array, find a pair summing to a target: move the left pointer up when the sum is too small and the right pointer down when it is too large โ O(n), and it is O(nยฒ) if you look at every pair.
Your practice task
Solve reverse-a-string-in-place, check-for-palindrome and pair-sum with two pointers, and write the complexity under each.
Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.
Key takeaway
Two pointers is one loop with two moving positions instead of two nested loops.
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
Almost there
15 lessons left of 15
Finish every lesson to unlock the certificate. Each one ends in a practice task โ do them and the final project brief writes itself.