Skip to content
CodeKruPro

Pair with a target sum in a sorted list

Coding problemEasyAsked in: Adobe, Amazon, Apple, Google, Meta, Microsoft

You are given a list of integers sorted from smallest to largest (values may repeat) and an integer target. Find two different positions i and j, with i < j, whose values add up to target, and return them as [i, j]. Positions count from 0.

If several pairs work, return any one of them. If no pair works, return [-1, -1].

The values can be as large as any 32-bit integer, so the sum of two values may not fit in 32 bits.

Examples

Example 1
Input: nums = [1,2,4,7,11], target = 9
Output: [1,3]
2 + 7 = 9.
Example 2
Input: nums = [-3,-1,0,2], target = -4
Output: [0,1]
Example 3
Input: nums = [1,2,3], target = 10
Output: [-1,-1]

Constraints

  • The list holds between 0 and 300,000 integers, sorted ascending
  • Every value and the target are 32-bit integers (between -2,147,483,648 and 2,147,483,647)

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

to answer and keep your progress. Reading is free for everyone.