Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft

A hash-map two-sum returns the first index pair (i, j), i < j, found while scanning left to right. What is printed?

A hash-map two-sum returns the first index pair (i, j), i < j, found while scanning left to right. What is printed?
def two_sum(a, t):
    seen = {}
    for j, x in enumerate(a):
        if t - x in seen: return (seen[t - x], j)
        seen[x] = j
    return None
print(two_sum([2, 1, 7, 5, 1, 1, 4, 8], 2))
  1. A. (1, 1)
  2. B. (3, 4)
  3. C. (1, 4)
  4. D. (1, 5)

Correct answer: C. (1, 4)

Checking for the complement BEFORE inserting x prevents pairing an element with itself; overwriting seen[x] keeps the latest index of repeated values. Output: (1, 4).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic