Data Structures & AlgorithmsHardTCS Digital · Infosys SP
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, 1, 2, 5, 1, 8, 1, 6], 9))- A. (4, 4)
- B. (4, 5)
- C. (3, 5)
- D. (1, 5)
Correct answer: B. (4, 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: (4, 5).
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
- Evaluate an infix expression of single digits with two stacks (operands and operators, usual precedence, left-associative). What is…
- Reverse a singly linked list in groups of k (a final group shorter than k is left as it is). What is printed? python def revk(h, k): cnt…
- Integer square root by binary search (largest m with m·m ≤ n). What is printed (root, iterations)? python n, lo, hi, it = 777, 0, 777, 0…
- Merge two sorted linked lists by relinking nodes (ties take the node from the first list). What is printed? python def merge(a, b): d = t…
- Binary search with mid = (lo + hi) // 2 (lo = 0, hi = n − 1, loop while lo ≤ hi) looks for 81 in [22, 26, 29, 31, 36, 38, 46, 51, 70, 81…
- The intervals [15, 16], [11, 16], [4, 9], [4, 8], [8, 12], [20, 22] are sorted by start and merged (intervals that touch, like [2, 4] and…