Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

Hash map counting: what is printed? (first element that repeats, scanning left to right)

Hash map counting: what is printed? (first element that repeats, scanning left to right)
def first_repeat(a):
    seen = set()
    for x in a:
        if x in seen: return x
        seen.add(x)
    return None
def first_with_dup(a):
    from collections import Counter
    c = Counter(a)
    return next((x for x in a if c[x] > 1), None)
a = [10, 5, 3, 4, 3, 5, 6]
print(first_repeat(a), first_with_dup(a))
  1. A. 5 3
  2. B. 3 5
  3. C. 3 3
  4. D. 5 5

Correct answer: B. 3 5

These answer different questions. first_repeat returns the first value whose SECOND occurrence comes earliest (3 repeats at index 4 before 5 repeats at index 5). first_with_dup returns the earliest element that has any duplicate: 5 (index 1). Both O(n).

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

Exams that ask this topic