SDE & MLE Prep

167. Two Sum II - Input Array Is Sorted

Problem

numbers is sorted in non-decreasing order. Return the 1-based indices [i, j] (i < j) of the two values that add up to target; exactly one such pair exists.

Example: numbers = [2,7,11,15], target = 9 → [1,2]

Constraints: O(1) extra space.

Sorted → if the sum is too small move l right, too big move r left. Each step discards one element that can't be in any answer.

[2, 7, 11, 15]  target 9
 l          r   2+15=17 > 9  -> r--
 l      r       2+11=13 > 9  -> r--
 l  r           2+7 = 9      -> [1, 2] (1-indexed)

Complexity: O(n) time, O(1) space.

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        l, r = 0, len(numbers) - 1
        while l < r:
            s = numbers[l] + numbers[r]
            if s == target:
                return [l + 1, r + 1]
            if s < target:
                l += 1
            else:
                r -= 1
        return []