DSA AnimatorDSA animations
Two Sum II LC #167 Medium Two Pointers
Problem

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Return their indices as [index1, index2] (1-indexed). You may not use the same element twice. Use only constant extra space.

Example 1
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: numbers[1] + numbers[2] = 2 + 7 = 9.
Example 2
Input: numbers = [2,3,4], target = 6
Output: [1,3]
Constraints: 2 ≤ numbers.length ≤ 3×104; -1000 ≤ numbers[i] ≤ 1000; numbers is sorted in non-decreasing order; -1000 ≤ target ≤ 1000; The tests are generated such that there is exactly one solution.
Try Examples
Custom:
Approach
Two Pointer on Sorted Array
L at start, R at end. Sum too small → L++ (get bigger left value). Sum too big → R-- (get smaller right value). Sum = target → found! O(n) time, O(1) space.
Array State
? + ?
=
Target
Variables
L
—
R
—
Sum
—
Target
—
Step Logic
Press ▶ Play or Next Step to begin.
✅
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
L=0, R=n-1
2
sum = nums[L] + nums[R]
3
sum == target → return [L+1, R+1]
4
sum < target → L++  |  sum > target → R--
Time
O(n)
Space
O(1)
Why It Works

Array is sorted. Sum too small → only moving L right can increase it (left value grows). Sum too large → only moving R left can decrease it (right value shrinks). This monotonicity guarantees we find the unique solution in a single pass — no brute-force needed.

How to solve Two Sum II

LeetCode 167 · Medium · Arrays · Pattern: Two Pointers

Why the obvious approach is slow

The brute force checks every pair, which is O(n²). A hash map gets it down to O(n) time, but it needs O(n) extra space, and that's not allowed here. Neither one uses the fact that the array is sorted.

The key idea

Put one pointer at the start and one at the end. If their sum is too big, the right number is too large, so move the right pointer left. If the sum is too small, move the left pointer right. Every move throws away a number that can never be part of the answer.

Remember

In a sorted array, two pointers from both ends find a pair in one pass. Sum too big, move right in. Sum too small, move left in.

Run the animation above on your own input, or watch the 1:56 video explanation of Two Sum II with a dry run and Java code.

More Arrays problems