Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Four price lists A, B, C, D (each of length n ≤ 500). Count index tuples (i, j, k, l) with A[i] + B[j] + C[k] + D[l] = 0 by hashing pair sums.

Problem: Four price lists A, B, C, D (each of length n ≤ 500). Count index tuples (i, j, k, l) with A[i] + B[j] + C[k] + D[l] = 0 by hashing pair sums.
from collections import Counter
def four_zero(A, B, C, D):
    ab = Counter(a + b for a in A for b in B)
    return sum(ab[-(c + d)] for c in C for d in D)
print(four_zero([1, 2], [-2, -1], [-1, 2], [0, 2]))
What is printed?
  1. A. 4
  2. B. 2
  3. C. 3
  4. D. 1

Correct answer: B. 2

Meet in the middle: count every A + B sum (n² entries), then for every C + D sum look up its negation. A + B sums: −1, 0, 0, 1. C + D sums: −1, 1, 2, 4 need 1, −1, −2, −4 → 1 + 1 = 2 tuples. Time O(n²) = 2.5·10⁵ lookups instead of the O(n⁴) ≈ 6·10¹⁰ brute force.

More Coding Interview Problems questions

Exams that ask this topic