167_Two Sum II - Input array is sorted

[easy] [array]

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.

  • You may assume that each input would have _exactly _one solution and you may not use the _same _element twice.

Example:

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Solution 1: Two Pointers

Idea:

  • We use two indexes, initially pointing to the first and last element respectively. Compare the sum of these two elements with target. If the sum is equal to target, we found the exactly only solution. If it is less than target, we increase the smaller index by one. If it is greater than target, we decrease the larger index by one. Move the indexes and repeat the comparison until the solution is found.

Time Complexity: O(n)O(n)

Space Complexity: O(1)O(1)

def twoSum(numbers, target):
    """
    :type numbers: List[int]
    :type target: int
    :rtype: List[int]
    """
    i, j = 0, len(numbers) - 1
    while i < j:
        if numbers[i] + numbers[j] == target:
            return [i+1, j+1]
        elif numbers[i] + numbers[j] < target:
            i += 1
        else:
            j -= 1

Idea:

  • Loop over each element in the input array, use binary search to search for the other part.

Time Complexity: O(nlogn)O(n\log{n})

Space Complexity: O(1)O(1)

def twoSum(numbers, target):
    """
    :type numbers: List[int]
    :type target: int
    :rtype: List[int]
    """
    for i in range(len(numbers)):
        l, r = i+1, len(numbers)-1
        tmp = target - numbers[i]
        while l <= r:
            mid = l + (r-l)//2
            if numbers[mid] == tmp:
                return [i+1, mid+1]
            elif numbers[mid] < tmp:
                l = mid+1
            else:
                r = mid-1

Last updated