Reading preferences
Concept

Merging Intervals

Combine overlapping closed ranges without losing coverage.

python, intervals, sorting, ranges

Combine overlapping coverage

Imagine closed time ranges where both endpoints count. Sort them by start, then extend the current range while the next starts at or before its end. A gap means the current range is complete.

Python illustration

def merge_ranges(ranges):
    merged = []
    for start, end in sorted(ranges):
        if not merged or start > merged[-1][1]:
            merged.append([start, end])
        else:
            merged[-1][1] = max(merged[-1][1], end)
    return merged

print(merge_ranges([(1, 3), (2, 5), (7, 8)]))

Prepared output: [[1, 5], [7, 8]].

See the reasoning

Follow the example one step at a time

Keep the union of closed ranges. This is a prepared teaching demonstration, not live code execution.

Start

current: [1, 3]
remaining: [2, 5], [7, 8]

Ranges are sorted by start.

Invariant and trade-offs

Assume each range has start <= end and comparable endpoints. After each iteration, merged represents exactly the processed coverage in disjoint ordered ranges. Nested and touching closed intervals are handled by the maximum endpoint. Half-open intervals or a policy that keeps touching intervals separate require a different overlap rule. Sorting takes O(n log n) time; the result and sorted copy use O(n) space. The input is not modified.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. Why sort ranges by their start?
2. Do closed intervals touching at an endpoint merge here?
3. What happens when a range is nested inside the current range?
4. What does an empty input return?

References and further reading