Sorted by start, every gap before a block is a free run
The obvious answer marks a slot for every unit of every block, then reads the runs off the slots. It's O(S) for an arena of S units, and a dump from the practice problem's 80 GiB arena makes that 85,899,345,920 slots. Say it and its cost, and move on.
The insight. This is free time from the intervals lesson, with one change. Sort the blocks by start and walk them with one number, free_from: every unit before it is in a block or already reported free.
- A block that starts after
free_fromleaves a gap, and that gap is a free run. - A block that starts before
free_fromoverlaps the one before it. In free time that was a meeting inside another meeting, handled withmax. Here it's corruption, and the answer is an error.
def free_runs_from_dump(size, blocks):
# every unit before free_from is used or reported
runs, free_from = [], 0
for start, n in sorted(blocks):
if n < 1 or start < free_from or start + n > size:
raise ValueError(f"block ({start}, {n}) is empty, overlaps the one before it, or runs past the end")
if start > free_from:
runs.append((free_from, start))
free_from = start + n
if free_from < size:
runs.append((free_from, size))
return runs
print(free_runs_from_dump(100, DUMP))
[(20, 40), (50, 52), (60, 70)]
Trace it the way you'd narrate it:
| Block | free_from before | Gap? | free_from after |
|---|---|---|---|
(0, 15) | 0 | no | 15 |
(15, 5) | 15 | no, it touches | 20 |
(40, 10) | 20 | (20, 40) | 50 |
(52, 8) | 50 | (50, 52) | 60 |
(70, 30) | 60 | (60, 70) | 100 |
free_from ended at 100, so there's no run at the end. No two of the runs touch, because a gap is reported only when a block starts after free_from, and two gaps always have a block between them.
largest_free(size, blocks) walks the dump the way free_runs_from_dump does, with free_from, but keeps only the longest gap. Write it for DUMP.