Given a sorted array of integers in non-decreasing order and a target sum, your task is to find a pair of numbers in the array that adds up exactly to the target value. The solution must use the two-pointer technique to achieve an O(n) time complexity and O(1) extra space.
If such a pair exists, return the indices (0-indexed) of the two numbers. If there are multiple valid pairs, return any one of them. If no such pair exists, return [-1, -1].
Given the array: [1, 2, 3, 4, 6]
and target sum: 8
, the pair (2, 6)
(indices [1, 4]
) adds up to 8
.
Today is Pi Day (March 14), a perfect day to celebrate circles, but also a good day to make your algorithms round the corner with efficient techniques like the two-pointer method!
Define a function that takes in a sorted array and a target integer, and returns an array of two integers representing the indices of the pair that sums up to the target.