Skip to content
{}

Lesson 27

Two Pointers

Two indices moving with purpose turn O(n²) pair searches into O(n).

16 min

01Why it matters & the intuition

Pair sums, palindromes, merging, deduplicating and container problems collapse from nested loops to one pass once you see the two-pointer pattern.

Think of it like…

Two people start at opposite ends of a sorted bookshelf looking for two books whose prices add to ₹500. If the pair is too expensive, the right person steps left to a cheaper book; too cheap, the left person steps right. Neither ever needs to go back.

02See it move

Press play, then step through slowly. Change the input and predict the next frame before you click.

Two pointers · pair sum
interactive
1/9
0
3
L
1
8
2
12
3
17
4
21
5
26
6
30
7
34
8
41
9
47
10
52
11
58
12
63
13
71
14
79
15
88
R
›Find two values that sum to 64. Start at both ends.
  • L / R
  • pair found
  • eliminated

03Key ideas

Opposite ends

On sorted input, left starts at 0 and right at the end. Each comparison lets you safely discard one end.

Same direction (fast/slow)

A slow pointer marks where to write, a fast pointer scans. Removes duplicates in place; on linked lists it finds the middle or detects cycles.

Why it's correct

Each move eliminates candidates that cannot be part of any answer, so skipping them never loses a solution.

04Build it from scratch

A clean reference implementation. Read it line by line — then close it and write your own in the lab below.

typescript
// Sorted input: find indices of two values summing to target.
function pairSum(sorted: number[], target: number): [number, number] | null {
  let left = 0;
  let right = sorted.length - 1;
  while (left < right) {
    const sum = sorted[left] + sorted[right];
    if (sum === target) return [left, right];
    if (sum < target) left++;  // need bigger
    else right--;              // need smaller
  }
  return null;
}

// Fast/slow: remove duplicates in place, return new length.
function dedupe(sorted: number[]): number {
  let write = 0;
  for (let read = 0; read < sorted.length; read++) {
    if (read === 0 || sorted[read] !== sorted[read - 1]) sorted[write++] = sorted[read];
  }
  return write;
}

05Complexity

OperationTimeSpace
Pair sum on sorted arrayO(n)O(1)
Palindrome checkO(n)O(1)
Brute-force alternativeO(n²)—

06Check your understanding

Question 1

Q1.Two pointers from both ends requires the array to be…

Question 2

Q2.If sum > target, you should…

Question 3

Q3.Fast/slow pointers can detect a cycle in a linked list because…

07Code lab

Write Python(or switch to JavaScript) and run it against real test cases. Python runs inside your browser — nothing is uploaded — and a C++ reference solution is under “Solution”.

Valid palindrome

Write is_palindrome(s) returning true if s reads the same forwards and backwards after lowercasing and ignoring every non-alphanumeric character. Use two pointers, no reversed copy.

function: is_palindromePython starts when you get here