Two Sum II — Input Array is Sorted

Difficulty: Easy 🏷️ Pattern: Two Pointers 🏢 Asked at: Amazon, Google, Microsoft, PhonePe


Problem

Given a 1-indexed sorted array numbers and a target, find two numbers that add up to target. Return their indices [i, j] where i < j.

Constraints:

Example:

Input:  numbers = [2, 7, 11, 15], target = 9
Output: [1, 2]   (numbers[1] + numbers[2] = 2 + 7 = 9)

Approach

Why Two Pointers?

The array is sorted. This is the trigger for Two Pointers:

Each step eliminates one candidate. We converge to the answer in at most n steps.

Why not HashMap?

HashMap works (O(n) time, O(n) space) but Two Pointers is O(n) time with O(1) space — strictly better when the input is sorted.


Complexity

  Time Space
Two Pointers O(n) O(1)
HashMap O(n) O(n)
Brute force O(n²) O(1)

Solution

public int[] twoSum(int[] numbers, int target) {
    int left = 0, right = numbers.length - 1;
    while (left < right) {
        int sum = numbers[left] + numbers[right];
        if (sum == target) return new int[]{left + 1, right + 1};
        else if (sum < target) left++;
        else right--;
    }
    return new int[]{-1, -1}; // unreachable per constraints
}
def twoSum(numbers, target):
    left, right = 0, len(numbers) - 1
    while left < right:
        s = numbers[left] + numbers[right]
        if s == target:
            return [left + 1, right + 1]
        elif s < target:
            left += 1
        else:
            right -= 1
    return [-1, -1]
vector<int> twoSum(vector<int>& numbers, int target) {
    int left = 0, right = numbers.size() - 1;
    while (left < right) {
        int sum = numbers[left] + numbers[right];
        if (sum == target) return {left + 1, right + 1};
        else if (sum < target) left++;
        else right--;
    }
    return {-1, -1};
}

Key Insight

When the array is sorted and you need to find a pair, Two Pointers from both ends gives you O(1) space. The sorted property guarantees that moving left right increases the sum, and moving right left decreases it — so you always make progress.


Follow-ups



Drop a comment below if you want a follow-up on 3Sum or Container With Most Water 👇

💬 Comments