InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Two Pointers

Two Sum II - Input Array Is Sorted

medium Original ↗ 00:00

Problem

You are given a 1-indexed array numbers, sorted in non-decreasing order, and a target integer. Exactly one pair of elements at distinct positions sums to the target. Return their 1-based indices [i, j] with i < j.

Two constraints distinguish this from plain Two Sum: the input is already sorted, and the solution must use O(1) extra space, which rules out a hash map.

Examples

Example 1

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

numbers[1] + numbers[2] = 2 + 7 = 9 (1-indexed).

Example 2

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

2 + 4 = 6. Note [2, 2] would be invalid — the same element can’t be used twice.

Example 3

Input:  numbers = [-4, -1, 0, 5], target = -5
Output: [1, 2]

-4 + -1 = -5. Negative values do not change the method.

Constraints

  • 2 <= numbers.length <= 3 * 10^4
  • -1000 <= numbers[i] <= 1000, -1000 <= target <= 1000
  • numbers is sorted in non-decreasing order.
  • Exactly one solution exists; O(1) extra space is required.

Think about it first

Hint 1 Use the sorted order. If you fix one element, how fast can you find its complement in a sorted array?
Hint 2 Try pointers at the two ends. If `numbers[left] + numbers[right]` is too small, which pointer can no longer be part of the answer at its current position?
Hint 3 If the sum is too small, `numbers[left]` has already been paired with the largest available partner and cannot reach the target, so `left += 1`. Too big, `right -= 1`. Equal, done. Each step discards one element, so the scan is linear and uses no extra memory.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug