Two Sum II (Sorted Array) Visualizer & Step-by-Step Algorithm Solution

Find two numbers in a 1-indexed sorted array that add up to a target number using opposing two pointers in O(n) time and O(1) space.

Category: arrays | Difficulty: Medium

Tags: Two Pointers, Array, Binary Search, Sorted Array

Two Sum II (Sorted Array)

Sorted Numbers Array (0-indexed)
2
0
7
1
11
2
15
3
100%
state
left
right
numbers[left]
numbers[right]
target9
length4
Initialization
1/15
Explanation

Start Two Sum II on sorted array [2, 7, 11, 15] with target 9.

Source Code
1function twoSum(numbers: number[], target: number): number[] {
2 let left = 0;
3 let right = numbers.length - 1;
4 while (left < right) {
5 const sum = numbers[left] + numbers[right];
6 if (sum < target) {
7 left++;
8 } else if (sum > target) {
9 right--;
10 } else {
11 return [left + 1, right + 1];
12 }
13 }
14 return [-1, -1];
15}