DSA · Patterns, not puzzles
How does the two-pointer technique work?
Short answer
Two pointers move through a sequence from opposite ends or in the same direction, reducing a nested scan to a single pass. It works when movement in one direction can safely discard part of the search space.
The pattern replaces a double loop with two indices. In the opposite-ends variant, one pointer starts at the beginning and one at the end, and they move inward. In the same-direction variant, a slow pointer tracks a write position while a fast pointer scans.
function twoSumSorted(values, target) {
let left = 0;
let right = values.length - 1;
while (left < right) {
const sum = values[left] + values[right];
if (sum === target) return [left, right];
if (sum < target) left += 1;
else right -= 1;
}
return [];
}When the pattern applies
- The input is sorted, or can be sorted without losing required information
- You need a pair, triplet or partition rather than an arbitrary subset
- Moving one pointer lets you rule out a whole set of candidates
- In-place removal or deduplication uses a slow write pointer
function removeDuplicates(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];
write += 1;
}
}
return write;
}Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does the opposite-ends variant require a sorted array?
- 2How would you return the original indices after sorting?
- 3When would you use a fast and slow pointer instead?
- 4How does this relate to the sliding window pattern?
Say it in the interview
Two pointers replace a nested scan with two indices that move according to a rule. For a sorted pair sum, I start at both ends and move the left pointer when the sum is too small or the right pointer when it is too large, because one side can be ruled out. A slow-fast variant works for in-place deduplication. The key requirement is that each move safely discards candidates.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.