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))- A. (0, 5)
- B. (3, 5)
- C. (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).
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
- A sorted array was rotated to give [29, 47, 50, 57, 60, 61, 75, 4, 5, 8, 13]. Binary search finds the index of the minimum: while lo < hi…
- Lines of heights [6, 9, 5, 6, 8, 1, 8, 3, 5] stand at x = 0, 1, …, 8. Two pointers find the pair of lines that, with the x-axis, holds the…
- Exponential search: double the bound i (1, 2, 4, …) until a[i] ≥ key or i passes the end, then binary-search the last range. How many…
- A Python 2-D list is created two ways and one cell is set. What is printed? python a = [[0] 3] 3 b = [[0] 3 for in range(3)] a[0][0] = 5…
- A circular queue in an array of size 7 keeps one slot empty to tell full from empty (front = rear means empty; (rear + 1) mod 7 = front…
- Count distinct values in every window of size k with a frequency map. What is printed? python from collections import Counter a, k = [4…