Data Structures & AlgorithmsHardFlipkart/Uber OA · placement

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([9, 9, 2, 2, 5, 1, 9, 1], 10))
  1. A. (0, 5)
  2. B. (3, 5)
  3. C. (4, 4)
  4. D. (1, 5)

Correct answer: D. (1, 5)

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, 5).

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

Exams that ask this topic