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?- A. 4 71 71 79 73
- B. 6 73 71 79 73
- C. 4 71 71 77 73
- 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
- Problem: Minimum cuts to split a string into palindromes: interval DP (pal table + cut array) versus the greedy 'always take the longest…
- Problem: Count Hamiltonian paths (visit every junction exactly once) in a 5-vertex road graph with bitmask DP over (visited set, current…
- Problem: a judge checks your rolling-hash solution with hash(s) = Σ s[i]·Bⁱ computed in unsigned 64-bit arithmetic (implicitly modulo…
- Problem: n ≤ 2·10⁵ values and q ≤ 2·10⁵ offline queries 'how many DISTINCT values are in a[l..r]?' (time limit 2 s). Which approach is…
- Problem: boxes (w, h) can nest when BOTH dimensions are strictly smaller. Find the longest nesting chain for n ≤ 2·10⁵. A candidate sorts…
- Problem: union–find runs m = 10⁶ operations on n = 10⁶ elements. Version X uses union by rank AND path compression; version Y uses path…