KatInterview

Collapse Booking Windows into Non-Touching Blocks

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

Last updated

Merge inclusive ranges that share at least one point into a sorted list of disjoint ranges, testing sorting, a linear sweep, and correct handling of touching endpoints and nesting.

Collapse Booking Windows

A scheduling tool stores reserved time windows as inclusive ranges of integers. Each window is a pair [lo, hi] that covers every integer value from lo through hi, including both ends.

Given a list of such windows in any order, combine windows that share at least one value so that the result contains only windows that are pairwise disjoint. The result must cover exactly the same values as the input, and be ordered by ascending lo.

Rule for combining

Take two windows [a, b] and [c, d] where a <= c. They are combined if and only if c <= b, that is, when they have at least one value in common.

  • Windows that touch at a single shared value, such as [1, 3] and [3, 5], are combined into [1, 5].
  • Windows that sit next to each other without sharing a value, such as [1, 2] and [3, 4], stay separate.
  • A window fully inside another is absorbed by it.
  • Identical windows collapse into one.
  • Windows with the same lo but different hi are combined, keeping the larger hi.

Task

Implement collapse_windows(windows) which returns the list of combined, pairwise disjoint windows sorted by lo.

  • If the input is empty, return an empty list.
  • Each returned window is a two-element list [lo, hi].

Constraints

  • 0 <= len(windows) <= 100_000
  • Each window has exactly two integers: windows[i] = [lo, hi]
  • -10^9 <= lo <= hi <= 10^9
  • The input windows may appear in any order.

Examples

Example 1

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

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

Example 2

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

Output: [[1, 5]]

Example 3

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

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

Hints

Hint 1

If the windows were ordered by their start value, which windows could possibly merge with the one you are currently building?

Hint 2

Sweep once over the sorted windows while keeping the last combined block. Compare the next start with that block's end, and think about whether the comparison should be strict or not given that shared endpoints count as overlap.

Hint 3

When extending the current block, set its end to the maximum of the old end and the new end, so a window nested inside the block does not shrink it.