KatInterview

Consolidate Overlapping Ranges

Greedy & IntervalsAuto-graded · 20 test cases
MediumAuto-gradedGreedy & Intervalsarrayssortinggreedy

Last updated

Tests ability to sort intervals and merge adjacent or overlapping ranges into a minimal disjoint set.

Consolidate Overlapping Ranges

You are given a collection of intervals, where each interval is represented as a pair [start, end]. Your task is to combine any intervals that overlap or touch into single, larger intervals, and return the resulting list of non-overlapping intervals.

Two intervals overlap if they share any point in common. Additionally, intervals that meet at a boundary point (for example, [1, 4] and [4, 5]) are considered overlapping and should be merged.

Write a function that takes a list of intervals and returns a new list containing only the merged, non-overlapping intervals that cover exactly the same range as the input.

Constraints

  • 1 <= intervals.length <= 10^4
  • Each interval [start, end] satisfies 0 <= start <= end <= 10^4
  • The input intervals may appear in any order
  • Intervals that share only a boundary point are considered overlapping

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

Start by sorting the intervals. Once sorted by their start points, overlapping intervals will be adjacent in the list.

Hint 2

After sorting, iterate through the intervals and maintain the last merged interval. Check if the current interval overlaps with or touches the last merged one.

Hint 3

Remember that one interval can be completely contained within another. Use the maximum of the end points when merging to handle this case correctly.