KatInterview

Consolidate Overlapping Time Intervals

Greedy & IntervalsAuto-graded · 21 test cases
MediumAuto-gradedGreedy & Intervalsintervalssortingarrays

Last updated

Evaluate ability to sort and combine overlapping or adjacent half-open numerical intervals in linear-arithmetic time.

Given a list of half-open intervals represented as pairs [start, end], combine all intervals that overlap or touch each other into a minimum set of disjoint intervals.

Two intervals [a, b] and [c, d] are considered touching if b == c or d == a. Zero-length intervals (where start == end) carry no length; if a zero-length interval falls within or touches another interval, it should be subsumed into the larger interval. If isolated, a zero-length interval [a, a] merges into itself or adjacent ranges as applicable.

The output list of merged intervals must be sorted by start time in ascending order.

Constraints

  • $0 \le \text{len}(intervals) \le 10^5$
  • Each interval is a list of two integers [start, end] where $\text{start} \le \text{end}$.
  • Interval endpoints are integers in the range $[-10^9, 10^9]$.

Examples

Example 1

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

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

Example 2

Input: merge_intervals([[1, 2], [3, 4]])

Output: [[1, 2], [3, 4]]

Example 3

Input: merge_intervals([[5, 5], [1, 3], [3, 3], [3, 6]])

Output: [[1, 6]]

Hints

Hint 1

Sorting the input list by the initial endpoint simplifies the overlap check significantly.

Hint 2

Once sorted, you only need to compare the current interval's start time with the end time of the most recently processed interval in your output list.

Hint 3

Because adjacent/touching intervals (where interval A's end equals interval B's start) must be combined, check for `start <= previous_end` rather than strict inequality.