0

Two Pointers (opposite ends)

Start one pointer at each end. Compare the current value against the target and move the pointer that can only improve the result.

Two PointersO(n) after sortingNew34 problems
18
mastery

Trigger phrases

If a problem statement sounds like one of these, try this pattern first.

sorted array
pair or triplet summing to target
container / area between two lines
palindrome check

The template

Get this into muscle memory, then adapt the condition per problem.

let l = 0, r = n - 1;
while (l < r) {
  const cur = a[l] + a[r];
  if (cur === target) return [l, r];
  cur < target ? l++ : r--;
}
Watch Two Pointers

If you are stuck

The generic hint ladder for this pattern, in order.

  1. 1Does sorting lose information you need? Usually not when only values matter.
  2. 2From the ends, one move increases the sum and the other decreases it.
  3. 3Skip duplicates after recording an answer to avoid repeats.

Drill it

Every problem in the bank that uses this pattern.

0 / 34 solved
1
MTwo Pointers
2
3
4
5
MLinked List
6
HTwo Pointers
7
8
ETwo Pointers
9
ETwo Pointers
10
MTwo Pointers
11
12
13
14
15
MTwo Pointers
16
MTwo Pointers
17
18
19
20
21
22
EBinary Search Tree
23
24
25
26
27
28
29
MStrings
30
MLinked List
31
32
33
34