KatInterview

Consolidate Overlapping Ranges

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

Last updated

Tests interval merging with sorting, overlapping logic, and immutability constraints

You are given a collection of closed ranges, where each range is represented as a pair [start, end] with start <= end. Your task is to combine all ranges that overlap or meet at their boundaries into a minimal set of non-overlapping ranges.

Two ranges are considered mergeable if one ends exactly where the other begins, or if they share any common values. For example, [3, 7] and [7, 10] should merge into [3, 10] because they meet at boundary point 7. However, [3, 5] and [6, 8] remain separate because no value belongs to both ranges.

Write a function that consolidates the input ranges and returns the minimal list of merged ranges.

Requirements:

  • The output must be sorted by starting position
  • Do not modify the input list or any of its elements
  • Empty input should produce empty output
  • Handle ranges in any order, including duplicates and single-point ranges (where start equals end)
  • Support negative values

Constraints:

  • 0 <= len(intervals) <= 100000
  • Each range contains exactly two integers
  • -10^9 <= start <= end <= 10^9

Examples

Example 1

Input: consolidate_ranges([[1, 3], [2, 6], [8, 10], [10, 12]])

Output: [[1, 6], [8, 12]]

Example 2

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

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

Hints

Hint 1

Start by organizing the ranges in a consistent order - what property makes sense to sort by?

Hint 2

Once sorted, can you process ranges in a single pass while tracking the current merged range?

Hint 3

When does a new range extend the current block versus starting a completely new block? Pay attention to the boundary-touching rule.