DSA

Two Sum II - Input Array Is Sorted

Two Pointer approach. Optimal — Time O(n), Space O(1).

August 8, 2026

Leetcode

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. Let these two numbers be numbers[index1] and numbers[index2] where 1 &lt;= index1 < index2 &lt;= numbers.length.

Return the indices of the two numbers index1 and index2, each incremented by one, as an integer array [index1, index2] of length 2.

The tests are generated such that there is exactly one solution. You may not use the same element twice.

Your solution must use only constant extra space.

Two Pointer Approach#

Since the array is sorted, place one pointer at the left end (smallest element) and one at the right end (largest). If their sum exceeds the target, the right pointer moves left to reduce the sum. If the sum is too small, the left pointer moves right to increase it. Because the array is sorted, each pointer move is guaranteed to bring the sum closer to the target — no element is skipped and the pair is found in a single linear pass. This achieves O(n) time with O(1) space, satisfying the constant-space constraint.

  • Leveraging sorted order of the array
cpp
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int n = numbers.size();
        int left = 0, right = n - 1;
        while(left <= right){
            int discoveredSum = numbers[left] + numbers[right];

            if(discoveredSum > target){
                right--;
            }else if(discoveredSum < target){
                left++;
            }else{
                return {left+1, right+1};
            }
        }
        return {-1,-1};
    }
};

Time Complexity: O(n)

Space Complexity: O(1)

img.png