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))- A. 5 3
- B. 3 5
- C. 3 3
- 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).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (anagram check two ways) python from collections import Counter x, y = "listen", "enlists" print(sorted(x) == sorted(y)…
- Binary search: how many iterations does this loop run to find x = 23? python a = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] lo, hi, it = 0…
- What is printed? (run-length decode then re-encode) python import re enc = "a3b1c12" dec = "".join(ch int(n) for ch, n in…
- What is printed? (move zeros to the end keeping order) python a = [0, 1, 0, 3, 12, 0, 5] w = 0 for r in range(len(a)): if a[r] != 0: a[w]…
- What is the time complexity of deleting the last node of a singly linked list of n nodes when only a head pointer is kept?
- A stack is implemented with a singly linked list. Where should push and pop operate to keep both O(1)?