Two pointers pattern for coding interviews
The two pointers pattern walks two indexes through a sequence so that each step rules out work a nested loop would repeat, which usually turns O(n²) into O(n). Use opposite-end pointers on sorted data or symmetric checks, a read pointer and a write pointer to filter an array in place, and fast and slow pointers on linked lists. The test is whether each pointer only ever needs to move in one direction.
By Evin JohnPublished 7 min read
How to spot it
A brute force that compares every element with every other element is the usual starting point. Two pointers apply when you can argue that, after comparing two positions, one of them never needs to be looked at again. On a sorted list, if the smallest plus the largest is too small, the smallest cannot be part of any answer with anything, so it can be dropped. In a palindrome check, once the outer characters match, only the inside is left. That one-way movement is the whole trick, and saying it out loud is how you prove the O(n) bound to an interviewer.
| Shape | Clue in the prompt | Pointers move |
|---|---|---|
| Opposite ends | Sorted input; pairs or triples with a target sum; symmetry | Left moves right, right moves left, until they meet |
| Read and write | "In place", "O(1) extra space", remove or compact | Both move right; write lags behind read |
| Fast and slow | Linked list; detect a loop; find the middle | Fast moves two steps for each step of slow |
| Two inputs side by side | Merge or intersect two sorted lists | Each pointer advances in its own list |
Template: opposite ends
Start one pointer at each end and move whichever one the comparison says can be discarded. Here the check is whether a string reads the same forward and backward, ignoring spaces, punctuation and case. Skipping a character that does not count, or matching two that do, always moves a pointer inward.
def is_palindrome(text):
i, j = 0, len(text) - 1
while i < j:
if not text[i].isalnum():
i += 1
elif not text[j].isalnum():
j -= 1
elif text[i].lower() != text[j].lower():
return False
else:
i, j = i + 1, j - 1
return Truefunction isPalindrome(text) {
const ok = c => /[a-z0-9]/i.test(c);
let i = 0, j = text.length - 1;
while (i < j) {
if (!ok(text[i])) i++;
else if (!ok(text[j])) j--;
else if (text[i].toLowerCase() !== text[j].toLowerCase()) return false;
else { i++; j--; }
}
return true;
}For pair sums on a sorted list, the moves are: if the sum is too small, move left inward; if too big, move right inward. Wrapping that inner scan in a loop over a fixed first element gives the classic triple-sum solution in O(n²). Skip equal neighbors so the same triple is not reported twice.
def three_sum_zero(values):
nums = sorted(values)
out = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
lo, hi = i + 1, len(nums) - 1
while lo < hi:
s = nums[i] + nums[lo] + nums[hi]
if s < 0:
lo += 1
elif s > 0:
hi -= 1
else:
out.append([nums[i], nums[lo], nums[hi]])
lo += 1
while lo < hi and nums[lo] == nums[lo - 1]:
lo += 1
hi -= 1
return outTemplate: read and write pointers
When a task says to modify an array in place, keep a write index for the next slot to fill and let a read index scan everything. Copy an element only if it should be kept. Removing duplicates from a sorted list, dropping every copy of a value, or moving zeros to the end all fit this shape.
def dedupe_sorted(values):
if not values:
return 0
write = 1
for read in range(1, len(values)):
if values[read] != values[write - 1]:
values[write] = values[read]
write += 1
return write # values[:write] holds the distinct valuesfunction dedupeSorted(values) {
if (values.length === 0) return 0;
let write = 1;
for (let read = 1; read < values.length; read++) {
if (values[read] !== values[write - 1]) values[write++] = values[read];
}
return write;
}Trace [1, 1, 2, 3, 3]: read finds 2 and 3 as new values, write ends at 3, and the first three slots hold [1, 2, 3]. Whatever is left after position write does not matter unless the interviewer says it does.
Template: fast and slow pointers
On a linked list you cannot index from the end, so you use speed instead. Move slow one node and fast two nodes per step. If the list ends, there is no cycle. If there is a loop, fast eventually laps slow and they land on the same node. When fast reaches the end of a list without a loop, slow is at the middle.
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
return True
return FalseTwo pointers and sliding windows
A sliding window is two pointers moving in the same direction with a rule about what may sit between them: extend the right edge, and advance the left edge when the rule breaks. Longest Substring Without Repeating Characters is the standard example. Merging is another relative: with one pointer in each of two sorted lists, take the smaller front element each time, which is the sweep behind Merge Intervals once the intervals are sorted.
Example problems to practice
- [Two Sum](/coding-problems/two-sum), sorted follow-up. The simplest opposite-ends scan; compare it with the hash map version for unsorted input.
- Triples that sum to zero. The code above; the difficulty is skipping duplicates correctly.
- Largest container between two walls. Given wall heights, pick two walls to hold the most water; always move the shorter wall inward, because the taller one cannot help a narrower container.
- Palindrome with one deletion allowed. On the first mismatch, check whether skipping the left or the right character leaves a palindrome.
- [Longest Substring Without Repeating Characters](/coding-problems/longest-substring-without-repeating-characters). Same-direction pointers with a last-seen map.
- Middle node and cycle start in a linked list. Fast and slow pointers; to find where a cycle begins, reset one pointer to the head after they meet and move both one step at a time.
Complexity
| Use | Time | Extra space |
|---|---|---|
| Opposite ends on sorted data | O(n), plus O(n log n) if you must sort first | O(1), or the sort's space |
| Triple sum after sorting | O(n²) | O(1) beyond the output |
| Read and write compaction | O(n) | O(1) |
| Fast and slow on a linked list | O(n) | O(1) |
| Merging two sorted lists | O(n + m) | O(n + m) for a new list |
Common mistakes
- Using opposite ends on unsorted data. The "too small, move left" logic is only valid when order tells you something.
- Forgetting the cost of sorting. If the input is not sorted, the total is O(n log n), and the original indexes are lost unless you keep them.
- Off-by-one in the loop condition. Use i < j for pairs; i <= j would compare an element with itself.
- Not skipping duplicates in triple-sum style problems, which produces repeated answers.
- Advancing fast two steps without checking both fast and fast.next first, which crashes when fast reaches the end of a list without a loop.
How to explain it out loud
Fictional example
- Candidate
- Comparing every pair of walls is quadratic. I'll put one pointer on each end instead.
- Candidate
- The water is limited by the shorter wall. If I moved the taller wall inward, the width shrinks and the height cannot get better, so that pair can be dropped. So I always move the shorter one.
- Candidate
- Each step moves one pointer inward and they never go back, so it is n steps and constant space.
If a problem's search space is ordered but not a single array, the binary search pattern is often the better tool; First Bad Version is the simplest case. See all walkthroughs on the coding problems hub.
Practicing with Natively
While you practice, Natively can read a problem from a screenshot on your Mac or Windows computer and suggest which two-pointer shape fits, so you can compare its reasoning with yours. It also keeps a transcript of a mock interview, which shows whether you explained why each pointer only moves one way. Read about the AI assistant for coding interviews.
Questions people ask
What is the two pointers technique?
Walking two indexes through a sequence so that each comparison lets one pointer move and never come back. Because neither pointer reverses, a nested loop's O(n²) work often drops to O(n).
When should you use two pointers?
On sorted data when looking for pairs or triples, for symmetric checks such as palindromes, for in-place filtering with O(1) extra space, and for cycles or middles in linked lists.
What is the difference between two pointers and a sliding window?
A sliding window is a kind of two pointers where both move in the same direction and the elements between them must satisfy a rule. Opposite-end and fast-and-slow pointers are the other common kinds.
Does the two pointers technique need a sorted array?
Opposite-end pair searches do, because order is what tells you which pointer to move. Read and write compaction and fast and slow pointers do not.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
