Two Numbers in Sorted Array with Sum K
EasyP1Coding
Given an array numbers sorted in non-decreasing order and an integer k, find two different elements whose sum is k. Return their indices (0-based) as [i, j] with i < j.
Exactly one valid pair exists. Use O(1) extra space.
Example 1
- Input
- numbers = [2,7,11,15], k = 9
- Output
- [0,1]
Example 2
- Input
- numbers = [2,3,4], k = 6
- Output
- [0,2]
Example 3
- Input
- numbers = [-1,0], k = -1
- Output
- [0,1]
Constraints
- 2 <= numbers.length <= 3 * 10^4
- -1000 <= numbers[i] <= 1000
- numbers is sorted in non-decreasing order.
- -1000 <= k <= 1000
- Exactly one valid pair exists.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 8. ⌘Enter runs, ⌘⇧Enter submits.