KatInterview

Consolidate Overlapping Ranges

Greedy & IntervalsAuto-graded · 25 test cases
MediumAuto-gradedGreedy & Intervalsintervalssortinggreedy

Last updated

Tests interval merging logic, correctly handling touching boundaries, nested ranges, and producing sorted disjoint output.

You receive a collection of closed ranges defined by integer boundaries. Each range may appear in any order. Your task is to consolidate all ranges that share at least one common point, then return the consolidated ranges in ascending order by their starting point.

Function Signature

def consolidate_ranges(ranges: list[list[int]]) -> list[list[int]]:

Each element ranges[i] = [start, end] represents a closed range including both start and end.

Rules

  • Two ranges share a common point when at least one integer belongs to both. For instance, [1, 4] and [4, 5] both contain the integer 4, so they must be consolidated. Conversely, [1, 2] and [3, 4] have no integer in common and remain separate.
  • Consolidation applies transitively: if range A shares a point with B, and B shares a point with C, then all three collapse into one range, regardless of whether A and C directly overlap.
  • When multiple ranges consolidate, the result spans from the minimum starting point to the maximum ending point across the entire group.
  • The input may include duplicate ranges or ranges fully contained within others.
  • Output the consolidated ranges in ascending order by starting point. Because consolidated ranges never overlap, this ordering is unambiguous.

Constraints

  • 1 <= len(ranges) <= 10^4
  • 0 <= start <= end <= 10^9 for every range

Examples

Example 1

Input: consolidate_ranges([[2, 5], [9, 12], [4, 7], [13, 15]])

Output: [[2, 7], [9, 12], [13, 15]]

Example 2

Input: consolidate_ranges([[6, 8], [1, 6]])

Output: [[1, 8]]

Example 3

Input: consolidate_ranges([[5, 7], [1, 2], [3, 4], [2, 3], [9, 9]])

Output: [[1, 4], [5, 7], [9, 9]]

Hints

Hint 1

What happens to overlapping ranges after you sort them by their starting point?

Hint 2

Once sorted, ranges that need consolidation will appear consecutively—you can process them in a single pass.

Hint 3

Remember that closed ranges touching at a single endpoint must merge, so use <= when comparing boundaries.