Algorithm patterns← All patterns

Pattern 01 / 10 · Fundamentals

Two Pointers

Walk in from both ends and let the data tell you which side to move.

The idea

Start one pointer at each end. Each step looks at the pair and moves exactly one pointer inward, so every step throws away a candidate that can never be the answer. One pass, no nested loop.

time O(n)space O(1)

Reach for it when

  • The array is sorted, or you can sort it without losing the answer.
  • You are looking for a pair (or triple) that meets a condition.
  • You need to compare or swap items from the two ends, like palindromes.

Watch it run

167. Two Sum II – Input Array Is Sorted

Given a sorted array, find the two numbers that add up to target and return their 1-based indices.

Example 1

Input: numbers = [2, 7, 11, 15], target = 9

Output: [1, 2]

Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2.

Example 2

Input: numbers = [2, 3, 4], target = 6

Output: [1, 3]

Explanation: The sum of 2 and 4 is 6. Therefore, index1 = 1, index2 = 3.

Example 3

Input: numbers = [-1, 0], target = -1

Output: [1, 2]

Explanation: The sum of -1 and 0 is -1. Therefore, index1 = 1, index2 = 2.

WALKTHROUGH INPUT · numbers = [1, 3, 4, 6, 8, 11, 14], target = 17

L
1
0
3
1
4
2
6
3
8
4
11
5
R
14
6
target = 17sum = –

Put left at the start (index 0) and right at the end (index 6).

1 / 5
solution.ts
1function twoSum(numbers: number[], target: number): number[] {
2 let left = 0, right = numbers.length - 1;
3 while (left < right) {
4 const sum = numbers[left] + numbers[right];
5 if (sum === target) return [left + 1, right + 1];
6 if (sum < target) left++;
7 else right--;
8 }
9 return [];
10}

Practice next