Intervals
48 / 170IntervalsLesson 2 of 6About 53 min
Carry one open block through the pass, extend it when the next thing touches it, close it when it does not.
Here it is on plain integers rather than intervals: compress a sorted list into runs of consecutive values.
def compress_runs(values): if not values: return [] blocks = [[values[0], values[0]]] for value in values[1:]: if value <= blocks[-1][1] + 1: # touches or overlaps the open block blocks[-1][1] = max(blocks[-1][1], value) else: blocks.append([value, value]) # gap, so close and start fresh return blocks print(compress_runs([1, 2, 3, 7, 8, 10]))print(compress_runs([]))Three questions answered by the same sweep. union_length returns the total length covered, counting overlapping parts once. count_blocks returns how many separate connected blocks the intervals form. largest_gap returns the widest uncovered stretch between two blocks. Answer all three in a single pass each, carrying only how far coverage currently reaches. Do not build a list of merged intervals.
Tests
data = [[1, 3], [2, 6], [8, 10], [15, 18]]print(union_length(data), union_length([]), union_length([[1, 10], [2, 4]]))print(count_blocks(data), count_blocks([]), count_blocks([[1, 5]]))print(largest_gap(data), largest_gap([]), largest_gap([[1, 5]]))Output
Run tests to see output.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.