Data Structures & AlgorithmsVery hardProduct company OA
Problem: Total length covered by a set of intervals, and the length covered by EXACTLY one interval, using coordinate compression and a difference array.
Problem: Total length covered by a set of intervals, and the length covered by EXACTLY one interval, using coordinate compression and a difference array.
def covered(iv):
xs = sorted({x for s, e in iv for x in (s, e)})
diff = [0] * len(xs)
pos = {x: i for i, x in enumerate(xs)}
for s, e in iv: diff[pos[s]] += 1; diff[pos[e]] -= 1
total = run = 0; once = 0
for i in range(len(xs) - 1):
run += diff[i]
if run > 0: total += xs[i + 1] - xs[i]
if run == 1: once += xs[i + 1] - xs[i]
return total, once
print(covered([(1, 5), (3, 9), (12, 15), (14, 20), (2, 4)]))What is printed?- A. (18, 12)
- B. (16, 12)
- C. (16, 8)
- D. (26, 12)
Correct answer: B. (16, 12)
Compress all endpoints, add +1/−1 at starts/ends, and sweep: each elementary segment [xᵢ, xᵢ₊₁) has a constant coverage count. Coverage > 0: [1, 9] and [12, 20] → 16. Coverage exactly 1: [1, 2) (1), [5, 9) (4), [12, 14) (2), [15, 20) (5) → 12; [2, 5) and [14, 15) are covered at least twice. Adding the interval lengths (26) double-counts overlaps. O(n log n), independent of coordinate size.
More Coding Interview Problems questions
- Problem: Warehouses at positions a with daily shipments w; choose a hub position x minimising Σ wᵢ·|aᵢ − x|. Compare the weighted median…
- 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…