KatInterview

Consolidate Overlapping Time Ranges

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

Last updated

Tests whether a candidate can sort and linearly sweep a list of ranges to produce the minimal set of non-overlapping intervals covering all input.

Problem Statement

You are given a list of ranges, where each element is a two-element list [start, end] representing a closed range from start to end (inclusive). Two ranges are considered overlapping if they share any point, including a single endpoint.

Your task is to collapse all overlapping ranges into a single range covering both, repeating until no two ranges in your result overlap. Return the final list of non-overlapping ranges in any order. Ranges that share exactly one endpoint must be merged (e.g., [1, 4] and [4, 7] become [1, 7]).

A range [a, b] is entirely contained within [c, d] when c <= a and b <= d. Contained ranges must be absorbed: the result should be the outer range, not two separate entries.

Constraints

  • 1 <= len(ranges) <= 10^4
  • Each element of ranges has exactly 2 integers.
  • 0 <= start <= end <= 10^4 for every range.

Examples

Example 1

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

Output: [[1, 6], [8, 10], [15, 18]]

Example 2

Input: consolidate_ranges([[1, 4], [4, 5]])

Output: [[1, 5]]

Hints

Hint 1

If the ranges were sorted by their start value, what can you say about which ranges could possibly overlap with a given range?

Hint 2

Walk through the sorted list once, keeping track of the range you are currently building. When does the current range end, and when do you start a new one?

Hint 3

When extending the current range, is it always safe to take the new range's end as the updated boundary? Think about what happens when one range is completely inside another.