KatInterview

Combine Overlapping Time Intervals

Greedy & IntervalsAuto-graded · 20 test cases
MediumAuto-gradedGreedy & Intervalsarraysgreedy-intervalssorting

Last updated

Consolidate overlapping and adjacent closed intervals into a minimal list of disjoint intervals using sorting.

You are given a list of 2D integer arrays intervals where intervals[i] = [start_i, end_i] represents a closed numerical interval starting at start_i and ending at end_i.

Combine all overlapping or touching intervals so that the output contains no overlapping regions and completely covers all original inputs.

Two intervals [a, b] and [c, d] overlap or touch if $c \le b$ (assuming $a \le c$). In particular, intervals that share an endpoint (e.g., [1, 4] and [4, 5]) are considered overlapping and must be merged into a single interval [1, 5].

Return a list of non-overlapping intervals sorted by their starting point.

Constraints

  • $1 \le \text{intervals.length} \le 10^4$
  • $\text{intervals}[i].\text{length} == 2$
  • $0 \le start_i \le end_i \le 10^9$

Examples

Example 1

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

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

Example 2

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

Output: [[1, 5]]

Hints

Hint 1

Sorting the intervals by their starting value simplifies identifying overlaps to adjacent comparisons.

Hint 2

Iterate through the sorted intervals while keeping track of the current active interval.

Hint 3

If the next interval begins before or at the end of the active interval, extend the active interval's end using the maximum of both end points.