TheScalableDev
PatternsBeginner55 minO(n) time after sorting (O(n log n) if you must sort) · O(1) extra spaceFree

Pattern - Two Pointers

Status

How to spot a two pointers problem, the three shapes (opposite ends, same direction read and write, two sequences) with a template each, the careful argument for why discarding a pointer is safe, exact operation counts against brute force, 3Sum built on top with duplicate skipping, six problems traced step by step, and the inputs where the pattern breaks.

BestO(1)AverageO(n)WorstO(n)SpaceO(1)

Picture two fingers on a long ruler. In the first game you put one finger on each end and walk them toward each other, and every step you decide which finger can safely give up its mark because no answer can involve it any more. In the second game both fingers start at the left: a fast finger reads every mark and a slow finger writes down only the marks worth keeping, so the kept marks pile up behind the slow finger. In the third game you hold one finger on each of two rulers and always advance the finger that points to the smaller number. In all three games no finger ever walks backward, so the two fingers together travel at most about n marks, and a search that looks like all pairs (n squared) becomes one pass (n).

Builds on

  • Big-O notation — the pattern is sold on a complexity improvement, and you will be asked to count operations exactly.
  • Arrays in memory — pointers here are indices, and the pattern relies on O(1) access to any index and on in-place writes.
01recognition is free; the payoff is O(n) instead of O(n^2)

Spot it: when a problem is two pointers

Many interview problems ask about pairs: two numbers that add up to a target, two walls that hold the most water, two ends of a string that must match. The tempting first idea is to try every pair with a loop inside a loop. That works, but with a hundred thousand elements it means about five billion pair checks. two pointers is the technique that avoids this. You keep two positions in the data and, at each step, move one of them in a direction that you can prove cannot lose the answer. Each position only ever moves one way, so the whole search is a single pass.

You can recognize the pattern from the wording and from the shape of the input. The strongest signal is a sorted array together with a pair or triple target. Other signals are symmetry (palindrome), a request to rearrange or compact the array in place without extra memory, and two already-sorted sequences that must be merged or compared. Note the contrast with sliding window: a window keeps both pointers close and cares about the contiguous range between them, while two pointers cares about the two elements the pointers touch (or about what lies behind the slow pointer).

Phrase in the problemShapePointers startExample
sorted array, find two numbers with sum topposite ends0 and n-1Two Sum on a sorted input
maximize something between two positionsopposite ends0 and n-1Container With Most Water
is it a palindrome (ignoring punctuation)opposite ends0 and n-1Valid palindrome
find all triplets that sum to zerosort, fix one, opposite endsi+1 and n-13Sum
move zeroes to the end, keep ordersame directionboth at 0Move Zeroes
put 0s, 1s and 2s in order in placesame direction (or three regions)0, 0, n-1Sort Colors
merge two sorted lists or arraystwo sequences0 in eachmerge step of merge sort
Signal words and the shape they suggest

A quick test before you commit: ask 'if I move this pointer, do I know whether the quantity I care about goes up or down?'. If the answer is yes for both pointers, you can build a safe rule. If the answer is 'it depends on values I have not seen', two pointers will give wrong answers and you should look at hashing, a window with prefix sums, or dynamic programming.

Check yourself

Which problem is the best fit for converging two pointers?

02from 4,999,950,000 checks to 99,999 steps

The numbers: all pairs versus one pass

Take the simplest problem: a sorted array of n numbers and a target. Does some pair add up to the target? The brute force fixes the first element, scans the REST, and moves on. For the first element there are n - 1 partners, for the second n - 2, and so on, so in the worst case (no pair exists) it makes (n-1) + (n-2) + ... + 1 comparisons. That sum is n(n-1)/2, the number of pairs.

brute = n(n-1)/2 two pointers <= n - 1 sort first ~ n log2(n)
Worst-case comparisons. Each two-pointer iteration shrinks the range [left, right] by exactly one index, and the range starts with n indices and loop stops at 1.
nBrute force n(n-1)/2Two pointers n-1Ratio
72163.5x
104595x
1,000499,500999500x
100,0004,999,950,00099,99950,000x
Exact worst-case counts (checked by running both versions in node)

Why at most n - 1? Each iteration moves exactly one pointer by exactly one step, and the loop runs while left < right, so the gap right - left starts at n - 1 and drops by one each time until it reaches 0. That is at most n - 1 iterations, and each iteration does one addition and one comparison, so the work is O(n) with O(1) extra memory.

The catch is that the array must be sorted. If it is not, sorting costs about n log2(n) comparisons. For n = 100,000, log2(n) is about 16.61, so sorting costs about 1,660,964 comparisons. That is still tiny compared to five billion: sort plus two pointers is about 1.76 million operations. The total is O(n log n) because the sort dominates. If the same array is searched many times (many different targets), you sort once and then every query is O(n).

100,000 x log2(100,000) ~ 100,000 x 16.61 = 1,660,964 + 99,999 ~ 1.76 million
Sort first, then converge: far below the 4,999,950,000 pair checks of brute force.

Check yourself

A sorted array has n = 1,000 elements and no pair matches the target. At most how many iterations does the converging loop run?

03O(n) time · O(1) space

Shape one: opposite ends converging, and why discarding is safe

In the first shape the pointers start at opposite ends, left = 0 and right = n - 1, and walk toward each other. The loop runs while left < right. At each step you look at the two elements, compute something (a sum, an area, a comparison), and then move exactly one pointer inward. The whole skill is knowing which one.

Two Sum on a sorted array. Output: [1, 5], [], [0, 1].
1function twoSumSorted(a, target) {
2 let left = 0, right = a.length - 1;
3 while (left < right) {
4 const sum = a[left] + a[right];
5 if (sum === target) return [left, right];
6 if (sum < target) left++; // too small: the left value is useless
7 else right--; // too big: the right value is useless
8 }
9 return [];
10}
11console.log(twoSumSorted([1, 3, 4, 6, 8, 11, 15], 14)); // [1, 5]
12console.log(twoSumSorted([1, 2, 3], 100)); // []
13console.log(twoSumSorted([2, 7, 11, 15], 9)); // [0, 1]

Now the part interviewers want to hear: why is discarding safe? State an invariant first: at the top of every iteration, if any pair in the whole array sums to the target, then some such pair has both indices inside the current range [left, right]. At the start the range is the whole array, so this is true.

Suppose the invariant holds and a[left] + a[right] < target. Take any index j with left < j <= right. Because the array is sorted ascending, a[j] <= a[right], so a[left] + a[j] <= a[left] + a[right] < target. So left cannot be the first element of a matching pair whose partner is inside the range. Partners outside the range were already removed, and by the invariant a matching pair (if any) lies inside. Therefore no matching pair uses left, and moving left forward keeps the invariant. The case a[left] + a[right] > target is the mirror image: a[i] >= a[left] for every i in the range, so a[i] + a[right] >= a[left] + a[right] > target, and right can be dropped.

Equal sums stop the loop with a hit. If the problem asks for every pair, the sum === target branch must record the pair and then move both pointers (and skip duplicates, as the 3Sum section shows); a branch that records and moves nothing loops forever.

Valid Palindrome: compare from both ends, skipping non-alphanumeric characters. Output: true, false, true.
1function isPalindrome(s) {
2 const isAlnum = (ch) => /[a-z0-9]/i.test(ch);
3 let left = 0, right = s.length - 1;
4 while (left < right) {
5 while (left < right && !isAlnum(s[left])) left++;
6 while (left < right && !isAlnum(s[right])) right--;
7 if (s[left].toLowerCase() !== s[right].toLowerCase()) return false;
8 left++;
9 right--;
10 }
11 return true;
12}
13console.log(isPalindrome('A man, a plan, a canal: Panama')); // true
14console.log(isPalindrome('race a car')); // false
15console.log(isPalindrome('')); // true

Here both pointers move on a match, and the safety argument is simpler: a palindrome requires s[i] to equal s[n-1-i] for every i, so each comparison checks one required pair and finishes it. The inner loops also guard with left < right so the pointers never cross while skipping punctuation. See the full exercise at Valid Palindrome.

Check yourself

Sorted ascending, a[left] + a[right] < target. Why is it safe to discard left?

04O(n) time · O(1) space

Converging with a different rule: Container With Most Water

You are given n wall heights. Choose two walls; the container holds water up to the shorter wall, over a width equal to the distance between them. Area = min(h[left], h[right]) * (right - left). Find the maximum area. Brute force tries all n(n-1)/2 pairs. converging pointers start at the widest container, which has the maximum width, and shrink the width by one each step, so the only way to improve is to find a taller shorter-wall.

Output: 49 and 1.
1function maxArea(h) {
2 let left = 0, right = h.length - 1, best = 0;
3 while (left < right) {
4 const area = Math.min(h[left], h[right]) * (right - left);
5 if (area > best) best = area;
6 if (h[left] < h[right]) left++; // shorter wall limits the height: drop it
7 else right--;
8 }
9 return best;
10}
11console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])); // 49
12console.log(maxArea([1, 1])); // 1

Why is moving the shorter wall safe? Suppose h[left] <= h[right]. Consider any container that keeps left but uses a closer right end j < right. Its width is j - left, which is smaller than right - left, and its height is min(h[left], h[j]) <= h[left] = min(h[left], h[right]). Both factors are no larger than in the container we just measured, so its area is no larger. Every container that uses left with a smaller right end is therefore at most the area we already recorded, so left can be discarded without losing the optimum. When h[left] == h[right], either pointer may move.

Why is moving the taller wall wrong? Take the same situation and discard right instead. A container with left and a closer right end j has a smaller width and a height capped by h[left], so it can only be worse; but a container with right and a closer left end could be better. By discarding right you may throw away the best container. Moving the shorter side is the only move that has a proof.

On [1, 8, 6, 2, 5, 4, 8, 3, 7] the loop runs 8 times (n - 1) and the areas it sees are 8, 49, 18, 40, 16, 15, 4, 6. The best is 49, between index 1 (height 8) and index 8 (height 7): min(8, 7) * 7 = 49. The Trace tab walks through the first steps. Related: Trapping Rain Water uses the same converging idea with two running maxima.

Check yourself

In maxArea, h[left] = 3 and h[right] = 9. Which pointer moves, and why?

05O(n) time · O(1) space, in place

Shape two: fast and slow in the same direction (read and write)

In the second shape both pointers start at the left and move right. The fast pointer, called read, looks at every element exactly once. The slow pointer, called write, marks the next position where a kept element will be stored. Elements the problem wants to remove or push to the back are skipped by write. This is how you compact or partition an array in place, in one pass, with no second array.

Remove duplicates from a sorted array in place. Output: 5 and [0, 1, 2, 3, 4].
1function removeDuplicates(a) {
2 let write = 0;
3 for (let read = 0; read < a.length; read++) {
4 if (write === 0 || a[read] !== a[write - 1]) {
5 a[write++] = a[read]; // keep: first copy of a new value
6 }
7 }
8 return write; // new length
9}
10const x = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4];
11const len = removeDuplicates(x);
12console.log(len, x.slice(0, len)); // 5 [0, 1, 2, 3, 4]

The sorted order is what makes duplicates sit next to each other, so comparing a[read] with the last kept value a[write - 1] is enough. The same skeleton handles other compaction tasks by changing the keep test.

Move Zeroes: keep the order of non-zero values. Output: 3 swaps and [1, 3, 12, 0, 0].
1function moveZeroes(a) {
2 let write = 0, swaps = 0;
3 for (let read = 0; read < a.length; read++) {
4 if (a[read] !== 0) {
5 if (read !== write) {
6 [a[write], a[read]] = [a[read], a[write]];
7 swaps++;
8 }
9 write++;
10 }
11 }
12 return swaps;
13}
14const z = [0, 1, 0, 3, 12];
15console.log(moveZeroes(z), z); // 3 [ 1, 3, 12, 0, 0 ]

Swapping instead of copying keeps the zeroes that were displaced at the back, so the single pass both compacts the non-zero values and fills the tail. The read !== write check skips pointless self-swaps when no zero has been seen yet. See Move Zeroes.

Partition by pivot (values below the pivot first). Output: 3 and [1, 2, 3, 5, 9, 7].
1function partition(a, pivot) {
2 let write = 0;
3 for (let read = 0; read < a.length; read++) {
4 if (a[read] < pivot) {
5 [a[write], a[read]] = [a[read], a[write]];
6 write++;
7 }
8 }
9 return write; // count of values below the pivot
10}
11const p = [5, 1, 7, 2, 9, 3];
12console.log(partition(p, 5), p); // 3 [ 1, 2, 3, 5, 9, 7 ]

This is the partition step of quicksort in its simplest form. It is not stable (the large values 7 and 9 ended up in reverse order), and that is fine for partitioning. Sorting three values, as in Sort Colors, extends this with a third pointer so that 0s go left, 2s go right, and 1s stay in the middle.

Check yourself

In removeDuplicates, what does the prefix a[0 .. write - 1] contain at the top of each iteration?

06O(n + m) time · O(1) extra beyond the output

Shape three: one pointer per sorted sequence

In the third shape you have two separate sorted sequences, and a pointer i into the first and a pointer j into the second. Because both are sorted, the smaller of a[i] and b[j] is the smallest remaining element overall, so you can decide it immediately and advance only that pointer. This is the merge step of merge sort, and it also computes set operations on sorted data.

Merge two sorted arrays. Output: [1, 2, 3, 4, 7, 9, 10].
1function mergeSorted(a, b) {
2 const out = [];
3 let i = 0, j = 0;
4 while (i < a.length && j < b.length) {
5 if (a[i] <= b[j]) out.push(a[i++]);
6 else out.push(b[j++]);
7 }
8 while (i < a.length) out.push(a[i++]); // leftovers of a
9 while (j < b.length) out.push(b[j++]); // leftovers of b
10 return out;
11}
12console.log(mergeSorted([1, 4, 7], [2, 3, 9, 10]));
Intersection of two sorted arrays, without repeats. Output: [2, 3, 8].
1function intersect(a, b) {
2 const out = [];
3 let i = 0, j = 0;
4 while (i < a.length && j < b.length) {
5 if (a[i] === b[j]) {
6 if (!out.length || out[out.length - 1] !== a[i]) out.push(a[i]);
7 i++;
8 j++;
9 } else if (a[i] < b[j]) {
10 i++; // a[i] is smaller than everything left in b
11 } else {
12 j++;
13 }
14 }
15 return out;
16}
17console.log(intersect([1, 2, 2, 3, 5, 8], [2, 2, 3, 4, 8, 9]));

Safety argument for the intersection: if a[i] < b[j], then b[j] is the smallest remaining element of b, so every remaining element of b is at least b[j] > a[i]. Nothing in b can equal a[i], and a[i] can be discarded. The mirror case discards b[j]. Each iteration advances at least one pointer, so the loop runs at most n + m times, where n and m are the lengths. In the merge, each iteration appends one element to the output, so it runs exactly n + m times in total including the leftover loops.

ShapeStarting positionsMove ruleStop when
opposite ends0 and n-1move the pointer the proof allows (too small: left; too big: right)left >= right
read and write0 and 0read always advances; write advances when an element is keptread reaches n
two sequences0 in a, 0 in badvance the pointer at the smaller valueeither sequence is exhausted
Choosing the shape

Check yourself

Intersecting sorted a = [1, 2, 3] and b = [3, 4]. At i = 0, j = 0 we see 1 versus 3. What happens?

07O(n^2) time · O(1) extra space beyond the output

Built on top: 3Sum with duplicate skipping

Find all unique triplets in an array that sum to zero. The brute force picks three indices: n(n-1)(n-2)/6 triplets, which is 166,167,000 for n = 1,000. The idea is to reduce it to the pair problem. Sort the array, fix the first element a[i], and look for two elements to its right that sum to -a[i]. That inner search is exactly the converging two-sum on the suffix a[i+1 .. n-1].

Output: [[-1,-1,2],[-1,0,1]], [[0,0,0]], [[-2,0,2]].
1function threeSum(nums) {
2 const a = [...nums].sort((x, y) => x - y);
3 const out = [];
4 for (let i = 0; i < a.length - 2; i++) {
5 if (a[i] > 0) break; // smallest value positive: no zero sum
6 if (i > 0 && a[i] === a[i - 1]) continue; // skip duplicate first values
7 let left = i + 1, right = a.length - 1;
8 while (left < right) {
9 const sum = a[i] + a[left] + a[right];
10 if (sum < 0) left++;
11 else if (sum > 0) right--;
12 else {
13 out.push([a[i], a[left], a[right]]);
14 left++;
15 right--;
16 while (left < right && a[left] === a[left - 1]) left++; // skip equal lefts
17 while (left < right && a[right] === a[right + 1]) right--; // skip equal rights
18 }
19 }
20 }
21 return out;
22}
23console.log(JSON.stringify(threeSum([-1, 0, 1, 2, -1, -4])));
24console.log(JSON.stringify(threeSum([0, 0, 0, 0])));
25console.log(JSON.stringify(threeSum([-2, -2, 0, 0, 2, 2])));

Duplicates are the main trap. In [-4, -1, -1, 0, 1, 2] the value -1 appears twice. Fixing i at the first -1 finds [-1, -1, 2] and [-1, 0, 1]. Fixing i at the second -1 would find the same two triplets again, so the code skips it with a[i] === a[i - 1]. Inside the pair search, after recording a triplet the code moves both pointers and then skips any values equal to the ones just used; otherwise [-2, -2, 0, 0, 2, 2] would report [-2, 0, 2] four times instead of once.

The comparison a[i] === a[i - 1] looks at the previous element, not the next. Skipping the next element instead would wrongly skip a triplet that uses two equal values, such as [-1, -1, 2], because the second -1 would be skipped before the pair search could use it.

Cost: sorting is O(n log n). For each of the roughly n values of i, the pair search is at most n - i - 2 iterations, so over all i the total is at most (n-2)(n-1)/2, which is 498,501 for n = 1,000, compared with 166,167,000 triplets for brute force. The overall time is O(n^2), because the quadratic term dominates the n log n sort. Extra space is O(1) besides the output (a few implementations of sort add O(log n) stack). Full exercise: 3Sum.

MethodOperationsFormula
brute force triple loop166,167,000n(n-1)(n-2)/6
sort + fix one + two pointers498,501 pair steps + about 9,966 for sorting(n-2)(n-1)/2 + n log2 n
3Sum counts for n = 1,000 (worst case)

Check yourself

In threeSum, why compare a[i] with a[i - 1] rather than a[i + 1] when skipping duplicates?

08wrong answers, not just slow ones

When two pointers does NOT apply

Every proof above leaned on a monotone fact: after moving a pointer, the sum, area or comparison changes in a known direction. When that fails the algorithm does not just run slowly, it returns wrong answers. Three situations break it.

Unsorted input. Run twoSumSorted on [3, 9, 1, 5] with target 6. The pair 1 + 5 = 6 exists at indices 2 and 3. The loop starts at 3 + 5 = 8 > 6, so right moves; then 3 + 1 = 4 < 6, so left moves and discards 3; then 9 + 1 = 10 > 6, so right moves, and left meets right. It returns [] and the pair was missed, because 'too big' no longer meant 'the right value is too big'.

Output: [] on unsorted input (wrong), then the sorted version finds the values.
1function twoSumSorted(a, target) {
2 let left = 0, right = a.length - 1;
3 while (left < right) {
4 const sum = a[left] + a[right];
5 if (sum === target) return [left, right];
6 if (sum < target) left++; else right--;
7 }
8 return [];
9}
10console.log(twoSumSorted([3, 9, 1, 5], 6)); // [] (wrong)
11console.log(twoSumSorted([3, 9, 1, 5].sort((x, y) => x - y), 6)); // [0, 2] (values 1 and 5)

Needing original indices. Sorting moves values, so the indices you find are indices in the sorted array. If the problem asks for the positions in the original input, as the classic Two Sum does, sort an array of pairs [value, originalIndex] and report the stored index, or simply use a hash map in O(n) time without sorting.

Non-monotone conditions. Counting or finding contiguous subarrays with a target sum looks like a two-pointer job, but with negative numbers it is not. For [5, -3, 3] with target 2, the subarray [5, -3] sums to 2. A read-and-shrink pointer scheme sees 5 > 2, discards the 5, and never recovers it, because removing 5 and adding later elements goes in unknown directions. The scheme finds 0 subarrays; brute force finds 1. The tools for that are prefix sums with a hash map.

SituationWhy pointers failUse instead
unsorted, only existence mattersno monotone rule for moving a pointerhash set (O(n)) or sort first (O(n log n))
need original indicessorting scrambles positionshash map, or sort pairs of value and index
subarray sum with negativesadding or removing an element can move the sum either wayprefix sums plus hash map, see sliding window
find k-th largest, order irrelevantpointers do not rankheap or quickselect
When to reach for something else

Check yourself

Why does converging two pointers return [] for unsorted [3, 9, 1, 5] with target 6 even though 1 + 5 = 6?

09each costs a wrong answer or a timeout on a hidden test

Common wrong turns

FailureImpactDefense
moving the wrong pointer (taller wall in the container, or left when the sum is too big)wrong answer: a valid pair is discardedwrite the proof for each branch; the pointer to move is the one whose element is provably finished
a branch that moves neither pointer (equal sum recorded, no left++ or right--)infinite loop, time limit exceededevery branch must change left or right; after recording a hit, move both
forgetting to skip duplicatesrepeated triplets in 3Sum outputskip equal first values (compare with the previous element) and equal pair values after a hit
while (left <= right) for pair problemsuses the same element twice: [3] with target 6 returns [0, 0]use left < right when two distinct elements are required
while (left < right) when each element must be checked alonethe middle element is never examineddecide whether the loop needs the pointers to be equal, e.g. a binary search needs <=
read-write: forgetting the new lengthcaller reads junk after writereturn write, and document that only a[0 .. write - 1] is valid
assuming the input is sortedsilently wrong answersask, or sort explicitly and mention the O(n log n) cost
Failure modes, impact and defense

The l <= r bug is worth seeing. With a = [3] and target 6, the loop with left <= right computes 3 + 3 = 6 and returns [0, 0], reporting a pair that uses the same element twice; with left < right the loop never starts and correctly returns []. For a = [1, 3, 5] and target 6, both versions return a pair, but the correct pair is found at [0, 2].

Why l < r is correct for pair problems: the pointers are distinct indices, and when they meet there is no pair left. Why l <= r appears elsewhere: in binary search a single remaining index is still a candidate that must be examined. Always ask 'does the last single element still need a decision?'.

Check yourself

twoSum uses while (left <= right) on a = [3] with target 6. What is returned?

10about 20 minutes

Timed interview script

  1. 01Restate (1 min)

    Repeat the problem and confirm: is the input sorted, can it contain duplicates, do you need indices or values, and what to return when nothing matches.

  2. 02Brute force (2 min)

    Describe all pairs and state the cost n(n-1)/2, which is 4,999,950,000 at n = 100,000. Mention the hash map alternative for unsorted input.

  3. 03Pointer idea (3 min)

    Pick the shape: opposite ends, read and write, or two sequences. Say where each pointer starts and which one moves in each case.

  4. 04Safety proof (3 min)

    State the invariant and the one-sentence reason a discarded element cannot be part of an answer. For containers, say the shorter wall caps the area.

  5. 05Code (8 min)

    Write the loop with left < right. Make sure every branch moves a pointer. Add duplicate skipping if triplets or unique results are needed.

  6. 06Verify and cost (3 min)

    Dry-run a small example, test empty, one element and all equal inputs, then state O(n) time, O(1) space, plus O(n log n) if you had to sort.

Recap

  • Recognize it: a sorted array with a pair or triple target, a symmetry check, an in-place partition or dedupe, or two sorted sequences to merge or intersect.

  • Three shapes: opposite ends converging, fast and slow in the same direction (read and write), and one pointer per sequence. Choose by where the pointers start.

  • converging pair sum: sum too small, move left; sum too big, move right. It is safe because the discarded index has no valid partner left in the current range.

  • Container with most water: always move the pointer at the shorter wall. Moving the taller wall cannot help because the width shrinks and the height is capped by the shorter wall.

  • Read and write: write marks the next slot for a kept element, read scans. Everything left of write is final. Move Zeroes uses 3 swaps on [0, 1, 0, 3, 12].

  • Merge two sorted sequences by advancing the pointer at the smaller value. Cost is n + m comparisons at most.

  • Counts: brute force over pairs is n(n-1)/2 (4,999,950,000 at n = 100,000). two pointers is at most n - 1 iterations (99,999). Sorting first costs about n log2 n (about 1.66 million).

  • 3Sum = sort, fix one index, converging pair search for the REST, skip duplicates at both levels. O(n^2) time, at most (n-2)(n-1)/2 pair-loop iterations.

  • It does not apply to unsorted input without sorting, when you need original indices (sort pairs of value and index), or when moving a pointer does not change the quantity in a known direction.

  • Wrong turns: moving the wrong pointer, a branch that moves neither pointer (infinite loop), forgetting duplicates, and l <= r instead of l < r.

Terms in this lesson

Every acronym and concept, expanded. Tap a term to open it.

sliding window

Keeping a range of the array and sliding its edges, instead of recomputing from scratch.

binary search

Halving a sorted search space each step to find a value in O(log n).

two pointers

Two indices that move through one array (or one index in each of two arrays) so that a search over pairs finishes in one pass.

Two fingers on a ruler.

merge sort

A divide-and-conquer sort that splits, sorts halves recursively, and merges them in O(n log n).

palindrome

A string that reads the same forward and backward.

partition

Reordering an array so every element smaller than a pivot comes before every larger one.

algorithm

A precise, step-by-step procedure that solves a problem.

invariant

A statement that is true at the top of every loop iteration. For converging pointers: if an answer exists, one exists with both indices inside the current range.

A promise the loop renews every time it comes back to the top.

hash map

A key-value store using a hash function for average O(1) lookups, inserts, and deletes.

hash set

A hash map that stores only keys, used to answer 'have I seen this?' in O(1).

in-place

An algorithm that rearranges data using only O(1) extra memory.

Big-O

Notation that describes how an algorithm's work grows as its input grows, ignoring constants and hardware.

array

A contiguous block of memory holding items in order, readable by index in O(1).

stack

A last-in-first-out structure: you push on top and pop from the top.

RESTRepresentational State Transfer

An API style built on plain HTTP verbs (GET, POST, PUT, DELETE) where each URL names a resource.

heap

A tree where each parent is more extreme than its children, giving O(1) access to the min or max.

converging

Pointers that start at opposite ends and walk toward each other until they meet.

Two people walking toward each other along a corridor.

read pointer

The fast index in the same-direction shape. It visits every element exactly once.

write pointer

The slow index in the same-direction shape. It marks the next position where a kept element is stored.

monotone

Moving in one direction only. Here it means: moving a pointer inward can only push a sum or an area in one known direction, which is what makes a decision safe.

exchange argument

A proof that discarding an option loses nothing: any solution using the discarded option can be swapped for one that is at least as good without it.

in place

Changing the input array itself using O(1) extra memory instead of building a second array.

duplicate skipping

Advancing a pointer past equal neighbours after you used a value, so the same triplet is not reported twice.

off-by-one

A boundary error of exactly one, such as writing l <= r where l < r is needed.

Where you will see it

Real systems that use this exact idea. Tap a card to open it.

Common traps

The mistakes interviewers watch for. Guess the fix, then reveal it.

  1. FixWrite the proof for each branch, move the pointer whose element is provably finished, and make sure every branch changes left or right.

  2. FixUse left < right for distinct pairs, and skip equal values (compare with the previous element) so each triplet is reported once.

  3. FixSort first (paying O(n log n)) or use a hash map, and carry [value, index] pairs when the original positions are required.

Interview prep

Questions you could be asked, with the depth an interviewer wants to hear.

I look for a sorted array with a pair or triple target, a symmetry check, an in-place compaction or partition, or two sorted sequences to merge. Then I ask whether moving a pointer changes the quantity in a known direction, because that is what makes a discard safe.

recognition: seconds

Real worldThe merge step of external sorting uses one pointer per sorted run.

DeeperWhat if the input is not sorted?