Data Structures & AlgorithmsEasyProduct Company SDE · Amazon/Microsoft-style OA
Problem: A delivery app logs the parcel weights of a day in an array. Return the indices of the two parcels whose weights add up exactly to a target (exactly one pair exists). Example: w = [4, 9, 2, 7], target = 11 → a pair such as (1, 2).
Problem: A delivery app logs the parcel weights of a day in an array. Return the indices of the two parcels whose weights add up exactly to a target (exactly one pair exists).
Example: w = [4, 9, 2, 7], target = 11 → a pair such as (1, 2).
def pair(w, target):
seen = {}
for i, x in enumerate(w):
if target - x in seen:
return (seen[target - x], i)
seen[x] = i
return None
print(pair([5, 1, 8, 3, 6], 9))What does this function print?- A. (0, 3)
- B. (2, 1)
- C. (3, 4)
- D. (1, 2)
Correct answer: D. (1, 2)
One pass with a hash map from value to index: at i = 2 (x = 8) the complement 1 is already stored at index 1, so (1, 2) is returned. The pair (3, 6) at indices (3, 4) also sums to 9 but is found later, and (0, 3) is 5 + 3 = 8. Time O(n), space O(n).
More Coding Interview Problems questions
- Problem: Given an unsorted array of n ≤ 10⁵ integers and a target, report whether two different positions hold values summing to the…
- Problem: A stock tracker gets daily prices and must report the best profit from one buy followed by one later sell (0 if no profit is…
- Problem: Find the largest sum of a non-empty contiguous block of an array (values may be negative). python def best(a): cur = ans = a[0]…
- Problem: Rotate an array to the right by k steps in place, using O(1) extra space. Example: [1, 2, 3, 4, 5], k = 2 → [4, 5, 1, 2, 3]…
- Problem: Every number in a list of sensor IDs appears twice except one. Find the lonely ID in O(n) time and O(1) space. python def…
- Problem: Return, for every index i, the product of all elements except a[i], without using division. Example: [1, 2, 3, 4] → [24, 12, 8…