KatInterview

Union Length of Half-Open Integer Intervals

Greedy & IntervalsAuto-graded · 24 test cases
MediumAuto-gradedGreedy & Intervalsintervalssortingsweep-line

Last 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.