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?
  1. A. (0, 3)
  2. B. (2, 1)
  3. C. (3, 4)
  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

Exams that ask this topic