Two Sum II - Input Array Is Sorted Using Two Pointers

Two Sum II - Input Array Is Sorted Using Two Pointers

·

1 min read

var twoSum = function (numbers, target) {
    let [start, end] = [0, numbers.length - 1];
    while (start < end) {
        const currentSum = numbers[start] + numbers[end];
        const isTarget = currentSum === target;
        if (isTarget) {
            return [start + 1, end + 1]
        }
        const isTargetLarger = currentSum < target;
        const isTargerSmaller = currentSum > target;
        if (isTargetLarger) {
            start++
        }
        if (isTargerSmaller) {
            end--;
        }
    }
    return [-1, -1]
};