KatInterview

Consolidate Overlapping Time Ranges

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

Last updated

Tests whether a candidate can sort and scan a list of closed intervals to collapse all overlapping or touching ranges into a minimal merged set.

Problem

You are given a collection of closed intervals, where each interval is represented as a two-element list [start, end] with start <= end. Two intervals should be joined together whenever they overlap or share an endpoint.

Your task is to collapse the collection into the smallest possible set of non-overlapping intervals that covers exactly the same set of points as the original input. Return the result sorted by the left endpoint of each interval.

Definitions

  • A closed interval [a, b] contains every integer point x with a <= x <= b.
  • Two intervals overlap if they share at least one point. This includes the case where one interval ends exactly where the next one begins (e.g., [1, 3] and [3, 5] share the point 3).
  • One interval is nested inside another if every point it covers is already covered by the other (e.g., [2, 4] is nested inside [1, 7]).

What to return

A list of intervals [start, end], sorted by start, such that:

  1. No two intervals in the output overlap or touch.
  2. Every point covered by at least one input interval is covered by exactly one output interval.

Constraints

  • 0 <= len(intervals) <= 10^4
  • -10^5 <= start <= end <= 10^5 for every interval
  • The input list may arrive in any order and may contain duplicate intervals.
  • Do not modify the input list or its sublists.

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

Try sorting the intervals by their left endpoint first — after sorting, any interval that can possibly overlap the current group must appear immediately after it, so a single left-to-right scan is enough.

Hint 2

As you scan, keep track of only the last merged interval. If the next interval's start is within (or touching) that interval's end, extend the end to whichever value is larger. Otherwise, the current group is complete — save it and start a new one.

Hint 3

Watch out for nested intervals like [1, 10] followed by [2, 3]: taking the new end naively would shrink your interval, so always take the maximum of the two ends when merging.