Coding Interview: Patterns & DSA · Arrays & Strings · Lesson 1 of 3
The two-pointer pattern
Two pointers walk through an array with two indices instead of nested loops, turning many O(n^2) scans into O(n). The pattern comes in two flavors: pointers moving toward each other from both ends, and pointers moving in the same direction at different speeds.
- Converging (opposite ends): start
left = 0,right = n-1, and move them inward based on a condition. Classic on sorted arrays. - Fast/slow (same direction): one pointer scans ahead while another marks a boundary — used for in-place filtering and dedup.
Example: pair sum in a sorted array
Given a sorted array, find two numbers that add up to a target. Brute force checks every pair in O(n^2). With two pointers you exploit the sort: if the current sum is too small, the only way to grow it is to move left right; if too big, move right left.
def two_sum_sorted(a, target): left, right = 0, len(a) - 1 while left < right: s = a[left] + a[right] if s == target: return [left, right] if s < target: left += 1 # need a bigger sum else: right -= 1 # need a smaller sum return []
Recognize itReach for two pointers when the input is sorted (or you can sort it), when you need pairs/triplets meeting a condition, or when you must edit an array in place. Say 'this drops us from O(n^2) to O(n) time, O(1) space.'
The same idea extends to reversing in place, palindrome checks, merging two sorted arrays, and 3-sum (fix one element, two-point the rest).
◆ Lock it in
- Two pointers replaces many nested loops — typically
O(n)time,O(1)space. - Converging pointers shine on sorted arrays; fast/slow does in-place filtering.
- Trigger words: sorted, pair/triplet, palindrome, in place, merge.
Feynman drill — say it out loudExplain why the sorted-array two-sum can safely move only one pointer per step without missing the answer.
Step 1 rate your confidence · Step 2 pick your answer
Two converging pointers on a sorted array most directly reduce which brute-force cost?
Step 1 — how sure are you?