Union Length of Half-Open Integer Intervals
Greedy & IntervalsAuto-graded · 24 test casesLast updated
Merge overlapping half-open intervals to return the total length covered by at least one interval.
You are given a list of intervals, each written as a pair [l, r) meaning the half-open range of real numbers from l up to but not including r. Several intervals may overlap, touch, be nested inside one another, or appear more than once. Some pairs may be degenerate or reversed (l >= r), in which case they cover nothing at all.
Compute the total length of the set of points that lie inside at least one interval. Because intervals are half-open, the length of a single interval [l, r) is r - l (not r - l + 1); the +1 convention only applies to closed integer intervals.
Overlapping regions must be counted exactly once. For example, [1, 4) and [2, 6) together cover [1, 6), a length of 5, not 7.
Intervals that merely touch, such as [1, 3) and [3, 5), together cover the contiguous range [1, 5) of length 4 — the same as treating them as separate pieces, so either view gives the same total. Coordinates may be negative or very large; do not assume any particular ordering of the input.
Return a single integer: the total covered length.
Constraints:
0 <= len(intervals) <= 2 * 10^5- Each interval is a pair of integers
[l, r]. -10^9 <= l, r <= 10^9- Intervals may be empty (
l >= r), duplicated, nested, or touching. - The covered length may exceed 32-bit range only in theory; return a plain Python int.
- Aim for
O(n log n)time.
Examples
Example 1
Input: union_covered_length([[1, 4], [2, 6], [8, 10]])
Output: 7
Example 2
Input: union_covered_length([[1, 5], [2, 3], [4, 8]])
Output: 7
Example 3
Input: union_covered_length([[-3, 0], [0, 2], [2, 5]])
Output: 8
Example 4
Input: union_covered_length([])
Output: 0
Hints
Hint 1
Sort the intervals by their left endpoint first; then you can process them in one left-to-right pass.
Hint 2
Keep a running block [start, end). If the next interval starts after end, the block is finished — add end - start and begin a new block.
Hint 3
When the next interval starts at or before end, extend the block with end = max(end, right). Drop intervals where l >= r before you start, since they cover nothing.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
The task is to measure the size of the union of half-open intervals. Summing each interval's r - l double-counts overlaps, so the plan is to first turn the input into a collection of pairwise disjoint blocks, then add up their lengths.
Approach (sort and sweep):
- Throw away degenerate intervals (
l >= r). They cover nothing, and a reversed pair would otherwise contribute a negative length. - Sort the remaining intervals by their left endpoint.
- Walk through them while maintaining one open block
[start, end):- If the current interval's left endpoint is strictly greater than
end, there is a genuine gap. The open block can never grow again, so addend - startto the total and start a new block at the current interval. - Otherwise the interval overlaps or touches the block, so extend it:
end = max(end, right).
- If the current interval's left endpoint is strictly greater than
- After the loop, add the final block's length.
Why it is correct: After sorting, any interval that could overlap the open block must begin at or before end; if some interval begins after end, every later interval begins at least as far right, so the block is sealed at its final length. Each sealed block is disjoint from every other block, and together the blocks cover exactly the union of the input. Adding the block lengths therefore gives the union length, with no point counted twice.
Complexity: Sorting costs O(n log n) time and the sweep is O(n), for O(n log n) overall. Extra space is O(n) for the sorted copy (or O(1) if sorted in place).
Notes and pitfalls:
- Length is
r - l, neverr - l + 1, because the intervals are half-open. - Touching intervals (
left == end) can be merged or not; the length is unaffected, and merging keeps the code simple. - Nested intervals are handled by
max(end, right)— the outer end wins. - Negative and very large coordinates need no special handling; only endpoint values matter, never array indexing by raw coordinate.
from typing import List
def union_covered_length(intervals: List[List[int]]) -> int:
intervals = sorted((left, right) for left, right in intervals if left < right)
if not intervals:
return 0
total = 0
start, end = intervals[0]
for left, right in intervals[1:]:
if left > end:
total += end - start
start, end = left, right
else:
end = max(end, right)
return total + end - start