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?- A. 4
- B. 2
- C. 3
- 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
- Problem: A hiking trail is a list of heights. Find the length of the longest 'ridge' – a contiguous stretch that strictly rises and then…
- Problem: Return the sum of min(sub) over all contiguous subarrays using a monotonic stack. Ties must be broken so every subarray's minimum…
- Problem: Pick two NON-overlapping windows of fixed lengths L and M (either order) to maximise the total of their elements. Prefix sums…
- Problem: Remove the SHORTEST contiguous block (not the whole array) so that the remaining sum is divisible by p; return −1 if impossible…
- Problem: Count contiguous subarrays whose MAXIMUM lies in [L, R]: count subarrays with max ≤ R and subtract those with max ≤ L − 1. python…
- Problem: Find the longest substring in which each vowel a, e, i, o, u occurs an even number of times. A 5-bit parity mask of the prefix is…