InterviewPrepKit

Home / Coding / Two Pointers

Two Sum II - Input Array Is Sorted

medium Original β†—
Solving tips
  • The sorted input plus O(1)-space constraint is the tell: skip the hash map and use converging pointers from both ends.
  • Compare the current sum against target: too small advances left (its largest partner already failed), too big retreats right; equal is the answer, in O(n) time and O(1) space.
  • The correctness certificate is that each comparison permanently eliminates one element, so at most n-1 steps reach the guaranteed unique pair.
  • Pitfall: the problem is 1-indexed, so return [left+1, right+1]; and never swap which pointer moves, since a small sum indicts left and a large sum indicts right.

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 extra rules distinguish this from plain Two Sum: the input is already sorted, and your solution must use O(1) extra space β€” so the usual hash map is off the table.

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; negatives change nothing about 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 The array being sorted is a gift. If you fix one element, how fast can you look for its complement in a sorted array?
Hint 2 Try pointers at the two ends. If `numbers[left] + numbers[right]` is too small, which pointer is provably useless where it stands?
Hint 3 Sum too small β†’ nothing pairs with `numbers[left]` (it already tried the largest available partner), so `left += 1`. Too big β†’ `right -= 1`. Equal β†’ done. Each step permanently discards one element, so the scan is linear and uses no memory.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.