Data Structures19 sections · 729 units
Open in Course

Two Sum Sorted - Implementation

Clean solution

Two pointers start at opposite ends of the sorted array:

function twoSum(numbers, target)
    left := 0
    right := length of numbers - 1

    while left < right
        sum := numbers[left] + numbers[right]
        if sum = target
            return [left + 1, right + 1]  // 1-indexed
        else if sum < target
            left := left + 1
        else
            right := right - 1

    return []  // no solution found

Time: O(n)O(n). Space: O(1)O(1).