Data Structures & AlgorithmsVery hardProduct company OA

Problem: Warehouses at positions a with daily shipments w; choose a hub position x minimising Σ wᵢ·|aᵢ − x|. Compare the weighted median, a brute-force minimum over 0..20, the rounded weighted mean and the unweighted median 6.

Problem: Warehouses at positions a with daily shipments w; choose a hub position x minimising Σ wᵢ·|aᵢ − x|. Compare the weighted median, a brute-force minimum over 0..20, the rounded weighted mean and the unweighted median 6.
def cost(a, w, x): return sum(wi * abs(ai - x) for ai, wi in zip(a, w))
a = [1, 4, 6, 10, 20]
w = [5, 1, 1, 1, 3]
wmed = None; acc = 0; half = sum(w) / 2
for ai, wi in sorted(zip(a, w)):
    acc += wi
    if acc >= half: wmed = ai; break
mean = sum(ai * wi for ai, wi in zip(a, w)) / sum(w)
print(wmed, cost(a, w, wmed), min(cost(a, w, x) for x in range(0, 21)), round(cost(a, w, round(mean)), 1), cost(a, w, 6))
What is printed?
  1. A. 4 71 71 79 73
  2. B. 6 73 71 79 73
  3. C. 4 71 71 77 73
  4. D. 8 79 71 79 73

Correct answer: A. 4 71 71 79 73

The cost is convex and piecewise linear; its slope at x is (weight left of x) − (weight right of x), so the minimum is where the cumulative weight first reaches half the total: weights 5 | 1 | 1 | 1 | 3 (total 11) reach 5.5 at position 4 → cost 71, equal to the brute-force minimum. The weighted mean (≈ 7.7 → 8) minimises SQUARED distance, not absolute: 79. The unweighted median 6 ignores weights: 73. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic