/Projects
Coding patterns · 01 of 15

Two pointers

Walk inwards from both ends of a sorted sequence.

PracticeCoding patternTier 2 · MechanismsApply15 minCore engineering

You will be able to: spot two pointers from a problem statement, and code it from memory.

Interview prepCoding patterns

Study with AI

O(n) time after sorting, O(1) extra space Watch as reels
Part 1 of 5

Basics

The idea behind the pattern, why it is correct, and the clues in a question that point to it.

1.1Core idea

What the pattern does, in plain words.

Put one pointer at each end. Compare, then move the pointer that can only improve the answer. Each step discards a whole row of possibilities, so you visit each element once.

Why it works

In a sorted array, the pair at lo and hi bounds every pair still possible. If their sum is too small, no pair using nums[lo] with anything at or left of hi can reach the target, so lo can move right; if it is too large, hi moves left. Each step rules out a whole row of pairs, so one pass is enough.

Typical cost: O(n) time after sorting, O(1) extra space

1.2Recognition signals

If a question has one of these clues, try this pattern first.

Sorted array or stringFind a pair or triplet with a target sumReverse, partition or remove in placePalindrome checks
Part 2 of 5

Question

A classic interview problem from this family. Read it carefully and plan the approach before writing any code.

2.13Sum

The problem statement, then the plan you would say out loud.

Problem

Return all unique triplets in nums that sum to zero.

Plan before you code

  1. Sort the array.
  2. Fix one number, then run two pointers on the rest for the negated value.
  3. Skip duplicates at every level so triplets stay unique.
Part 3 of 5

Detailed answer

First the reusable template, then the worked solution built from it and a walk through it one step at a time.

3.1Template

Memorise this shape. Most problems in this family are this code plus one twist.

Pair with target sum (sorted)

pair-target-sum.tsTypeScript
1function pairSum(nums: number[], target: number): [number, number] | null {2  let lo = 0, hi = nums.length - 1;3  while (lo < hi) {4    const s = nums[lo] + nums[hi];5    if (s === target) return [lo, hi];6    if (s < target) lo++;   // need a bigger sum7    else hi--;              // need a smaller sum8  }9  return null;10}
10 linesUTF-8TypeScript
  1. Start at both ends of the sorted array.
  2. Compare the current pair with the target.
  3. Move the pointer that can only improve the sum.

3.2Solution

Strict TypeScript, type-checked and tested.

3Sum

3sum.tsTypeScript
1function threeSum(nums: number[]): number[][] {2  nums.sort((a, b) => a - b);3  const out: number[][] = [];4  for (let i = 0; i < nums.length - 2; i++) {5    if (i > 0 && nums[i] === nums[i - 1]) continue;   // skip duplicate anchors6    let lo = i + 1, hi = nums.length - 1;7    while (lo < hi) {8      const s = nums[i] + nums[lo] + nums[hi];9      if (s < 0) lo++;10      else if (s > 0) hi--;11      else {12        out.push([nums[i], nums[lo], nums[hi]]);13        lo++;14        while (lo < hi && nums[lo] === nums[lo - 1]) lo++;   // skip duplicate seconds15      }16    }17  }18  return out;19}
19 linesUTF-8TypeScript

Step by step

  1. Sort numerically first (the default sort compares strings), so two pointers can steer the sum.
  2. Fix each anchor once and skip duplicate anchors.
  3. Two pointers on the rest: move towards a zero sum.
  4. Record the triplet, then skip duplicate seconds.

Complexity: O(n²) time, O(1) extra space beyond the output

Part 4 of 5

Q&A

What interviewers ask once your code works, and problems to try on your own.

4.1Interview questions

Answer out loud, then open.

Why must the array be sorted?
Sorting is what makes 'too small, so move lo' safe. Without order, moving a pointer could skip the answer. If you need the original indices and cannot sort, use a hash map instead.
Two pointers or a hash map for Two Sum?
A hash map is O(n) time on unsorted input but uses O(n) memory. Two pointers need sorted input and O(1) extra space. Say which constraint drives your choice.
How do you avoid duplicate triplets in 3Sum?
Sort first, skip an anchor equal to the previous anchor, and after recording a triplet move lo past values equal to the one just used.

4.2Solo practice

Try these without looking; open the hint only when stuck.

EasyValid Palindrome
Hint

Skip non-alphanumerics from both ends.

Part 5 of 5

Extra depth

More fully worked problems in the same family, and the mistakes that cost offers.

5.12 more worked problems

Each one: the problem, the plan, the code and its cost.

Show detailsHide details
Medium

Container With Most Water

Pick two lines that, with the x-axis, hold the most water.

  1. Start with the widest container.
  2. The shorter wall limits the area, so moving the taller wall can never help.
  3. Always move the shorter wall inwards.
container-most-water.tsTypeScript
1function maxArea(height: number[]): number {2  let lo = 0, hi = height.length - 1, best = 0;3  while (lo < hi) {4    const h = Math.min(height[lo], height[hi]);5    best = Math.max(best, h * (hi - lo));6    if (height[lo] < height[hi]) lo++;7    else hi--;8  }9  return best;10}
10 linesUTF-8TypeScript

Complexity: O(n) time, O(1) space

Hard

Trapping Rain Water

Given bar heights, how much rain water is trapped between them?

  1. Water above a bar = min(max left, max right) − height.
  2. Walk inwards from both ends.
  3. The side with the lower wall is already bounded, so settle it and move on.
trapping-rain-water.tsTypeScript
1function trap(height: number[]): number {2  let lo = 0, hi = height.length - 1;3  let leftMax = 0, rightMax = 0, water = 0;4  while (lo < hi) {5    if (height[lo] < height[hi]) {6      leftMax = Math.max(leftMax, height[lo]);7      water += leftMax - height[lo];8      lo++;9    } else {10      rightMax = Math.max(rightMax, height[hi]);11      water += rightMax - height[hi];12      hi--;13    }14  }15  return water;16}
16 linesUTF-8TypeScript

Complexity: O(n) time, O(1) space

5.2Traps

Bugs and misreadings that come up again and again with this pattern.

Show detailsHide details
  • Forgetting to sort first
  • Infinite loop when neither pointer moves
  • Duplicate answers without skip logic
AI Engineer · Two pointers