Back to Dashboard

Two Sum II - Input Array Is Sorted

Medium

Problem Statement

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 <= index1 < index2 <= numbers.length. Return the indices of the two numbers, index1 and index2, added by one and incremented by one.

Examples

Example 1:

  • Input: numbers = [2,7,11,15], target = 9
  • Output: [1,2]

Example 2:

  • Input: numbers = [2,3,4], target = 6
  • Output: [1,3]

Approach 1: Two Pointers

O(n)
O(1)
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        var l = 0;
        var r = numbers.length - 1;
        while (l < r) {
            var sum = numbers[l] + numbers[r];
            if (sum < target) {
                l ++;
            } else if (sum > target) {
                r --;
            } else {
                return new int[]{l + 1, r + 1};
            }
        }
        return new int[]{-1, -1};
    }
}

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

Two Pointers

Date

2026-02-07
View Problem Source