The Problem

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.

Return the indices of the two numbers, index1 and index2, added by one (1-indexed) as an integer array [index1, index2].

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.

Interactive Visualization

Speed:
Array Visualization
Code
fun twoSum(numbers: IntArray, target: Int): IntArray {    var left = 0; var right = numbers.size - 1    while (left < right) {        val currentSum = numbers[left] + numbers[right]        if (currentSum == target) {  // found it!            return intArrayOf(left + 1, right + 1)        } else if (currentSum < target) {  // need bigger sum            left++        } else {  // need smaller sum            right--        }    }    return intArrayOf() // no solution}
Status
Press Step or Play to begin.

How It Works

Key Insight

Because the array is sorted, we can use two pointers starting from opposite ends. If the current sum is too small, moving the left pointer right increases the sum. If the current sum is too large, moving the right pointer left decreases the sum. This guarantees we find the answer in a single pass without needing a hash map.

The Algorithm

  • Initialize: left = 0 (start of array), right = len(numbers) - 1 (end of array)
  • Each iteration: compute current_sum = numbers[left] + numbers[right]
  • If sum == target: return [left + 1, right + 1] (1-indexed)
  • If sum < target: we need a bigger sum, so move left pointer right (left += 1)
  • If sum > target: we need a smaller sum, so move right pointer left (right -= 1)
  • Guaranteed: exactly one solution exists, so the pointers will always meet at the answer

Complexity

Time O(n)
Space O(1)

Each pointer moves at most n steps total, and we use only two variables for the pointers โ€” no extra data structures needed.