Two Sum in Sorted Array

EasyTwo Pointerstwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an array numbers that is sorted in **non-decreasing** order, together with an integer target. Your task is to find two distinct positions in the array whose values add up exactly to target. Return the **1-indexed** positions of these two values as an integer array [i, j] where 1 <= i < j <= numbers.length. In other words, numbers[i-1] + numbers[j-1] == target. You may assume that each input has **exactly one** valid pair of positions, and you may not use the same position twice. If somehow no pair exists, return an empty array. Because the array is already sorted, aim for a solution that runs in O(n) time and uses only constant extra space.

Examples

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
numbers[0] + numbers[1] = 2 + 7 = 9, so the answer is positions 1 and 2.
Input: numbers = [2,3,4], target = 6
Output: [1,3]
numbers[0] + numbers[2] = 2 + 4 = 6, so the answer is positions 1 and 3.
Input: numbers = [-1,0], target = -1
Output: [1,2]
The only pair, -1 + 0 = -1, gives positions 1 and 2.

Constraints

  • 2 <= numbers.length <= 30000
  • -1000 <= numbers[i] <= 1000
  • numbers is sorted in non-decreasing order
  • -2000 <= target <= 2000
  • Exactly one valid pair of positions exists

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems