Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: The 'two-sum on a sorted array' code below has a subtle edge-case behaviour. What does it print?

Problem: The 'two-sum on a sorted array' code below has a subtle edge-case behaviour. What does it print?
def two_sum_sorted(a, t):
    i, j = 0, len(a) - 1
    while i <= j:
        s = a[i] + a[j]
        if s == t: return (i, j)
        if s < t: i += 1
        else: j -= 1
    return None
print(two_sum_sorted([1, 3, 5, 8], 10), two_sum_sorted([1, 3, 6], 12))
What is printed?
  1. A. (2, 2) (2, 2)
  2. B. None None
  3. C. (1, 3) None
  4. D. (2, 2) None

Correct answer: A. (2, 2) (2, 2)

With i <= j the pointers are allowed to meet, so one element is used twice. [1, 3, 5, 8], t = 10: 9 → i++, 11 → j−−, 8 → i++, then i = j = 2 and 5 + 5 = 10 is 'found'. Likewise 6 + 6 = 12. The loop must be while i < j to require two different positions (then both calls return None). O(n).

More Coding Interview Problems questions

Exams that ask this topic