call(back)
Algorithms & Data StructuresmediumSign in to star problems

Experiment Buckets II

Same bucket space [0, n). Existing experiments hold ranges of buckets, given as inclusive [start, end] pairs — possibly overlapping, possibly out of bounds (clamp them), and in no particular order. Return the unallocated buckets as a minimal sorted list of inclusive [start, end] ranges (adjacent free buckets merge into one range).

unallocatedRanges(10, [[2, 4], [6, 6]])  ->  [[0, 1], [5, 5], [7, 9]]

Hints

Hint 1

Sort ranges by start and sweep once with a cursor holding the smallest bucket not yet proven allocated: any gap before a range's start is free.

Hint 2

Advance the cursor with max(cursor, end + 1) — the max is what absorbs overlapping and fully-contained ranges. Emit the tail after the last range, and note why the sweep beats a boolean array when n is huge.

Asked at