Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft
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([2, 1, 7, 5, 1, 1, 4, 8], 2))- A. (1, 1)
- B. (3, 4)
- C. (1, 4)
- D. (1, 5)
Correct answer: C. (1, 4)
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, 4).
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 dynamic array doubles its capacity when full, copying all elements. Starting from capacity 1, what is the total number of element copies…
- Evaluate the postfix expression 7 4 1 ÷ 7 + 6 × 2 × + 3 − (all divisions are exact). What is its value, and what is the maximum number of…
- Asteroids move along a line: positive values move right, negative move left; on collision the smaller (by absolute value) explodes, equal…
- One Lomuto partition (pivot = LAST element; i marks the end of the 'less than pivot' region; when a[j] < pivot, increment i and swap a[i]…
- Keys 47, 74, 63, 43, 45, 59, 85 are inserted in this order into an empty table of size 13 using quadratic probing: probe i goes to (k mod…
- What does this loop-counting code print? (Python) python n, c = 300, 0 i = 2 while i <= n: c += 1 i = i i print(c)