KatInterview

Consolidate Half-Open Interval Ranges

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

Last updated

Tests interval merging with half-open semantics, distinguishing overlap from adjacency, and handling nested ranges correctly.

Problem

You are given a collection of half-open intervals representing time ranges. Each interval [start, end) includes the start time but excludes the end time. Your task is to combine all intervals that share at least one overlapping point, and return a sorted list of non-overlapping intervals.

Two intervals [a, b) and [c, d) overlap if and only if they share at least one point in common. Because the intervals are half-open, [1, 3) and [3, 5) do not overlap—the first excludes 3 while the second includes it—so they remain separate in the output.

Write a function consolidate_intervals(intervals) that takes a list of intervals and returns the consolidated result.

Constraints

  • 0 <= len(intervals) <= 200,000
  • Each interval [start, end) satisfies 0 <= start < end <= 10^12
  • The input may be unsorted and may contain duplicate or fully nested intervals
  • Output must be sorted by start time and contain no overlapping intervals

Notes

  • Adjacent intervals that merely touch at a boundary point should remain separate
  • When multiple intervals overlap, the merged interval should span from the earliest start to the latest end among them
  • Empty input should return an empty list

Examples

Example 1

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

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

Hints

Hint 1

Sort the intervals first—once sorted by start time, you only need to check whether each new interval overlaps with the most recent merged one.

Hint 2

For half-open intervals, two intervals [a,b) and [c,d) overlap when c < b (not c <= b). The strict inequality is critical.

Hint 3

When merging overlapping intervals, use max(current_end, new_end) to handle cases where a later interval is completely nested inside an earlier one.