Two Sum II - Input Array Is Sorted

MediumTwo Pointers · Sorted Array🧩 Two PointersLeetCode #167 ↗Updated

Problem

The array numbers is sorted in non-decreasing order. Find two different positions whose values add up to target and return them as 1-based indices [i, j] with i < j. Exactly one answer exists, and you may use only constant extra space.
Input[2,7,11,15], target=9Output[1,2]
Input[2,3,4], target=6Output[1,3]
Input[-1,0], target=-1Output[1,2]

2 ≤ n ≤ 3·104  ·  -1000 ≤ numbers[i], target ≤ 1000  ·  exactly one solution  ·  O(1) extra space

Try it yourself

Java
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
With the array sorted, the pair sum is monotonic in each pointer: too small → move the left pointer right, too big → move the right pointer left. Each move safely discards one element forever.
PatternTwo Pointers

Instinct Sorted input, a pair/triple hitting a target, or something symmetric? Put one pointer at each end and move the one that can only improve things.

Memory hack Squeeze from both ends - every step throws away a whole row of the brute-force grid.

Open the Two Pointers guide →

Approaches

Brute ForceCheck Every Pair

Time O(n2)Space O(1)

Try every pair (i, j) with i < j. Sorting lets us break the inner loop once the sum exceeds the target, but the worst case is still quadratic.

Java
public int[] twoSum(int[] numbers, int target) {
    for (int i = 0; i < numbers.length; i++) {
        for (int j = i + 1; j < numbers.length; j++) {
            int sum = numbers[i] + numbers[j];
            if (sum == target) return new int[]{i + 1, j + 1};
            if (sum > target) break; // sorted: only grows from here
        }
    }
    return new int[]{};
}

Trivially correct, ignores most of the sorted-order information.

At a glance

LevelApproachTimeSpace
Brute ForceCheck Every PairO(n2)O(1)
BetterBinary Search the ComplementO(n log n)O(1)
OptimalTwo Pointers from Both EndsO(n)O(1)
Common pitfalls
  • Returning 0-based indices — the problem wants 1-based.
  • Using a HashMap like Two Sum I — works but violates the O(1) space rule.
  • Binary search over the whole array can return i itself (e.g. 3+3=6).
Interview tips
  • Explain why discarding l or r is safe — that is the proof.
  • Contrast with Two Sum I: unsorted → hash map; sorted → two pointers.
  • This loop is the inner engine of 3Sum / 4Sum — say so.
Pattern
Opposite-end two pointers → pair search in a sorted array where the sum moves monotonically.
My notes saved in this browser