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?
  1. A. (18, 12)
  2. B. (16, 12)
  3. C. (16, 8)
  4. 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

Exams that ask this topic