KatInterview

Combine Two Ordered Schedules into One Gap-Free Timeline

Greedy & IntervalsAuto-graded · 22 test cases
MediumAuto-gradedGreedy & Intervalsintervalstwo-pointersmerge

Last updated

Merge two sorted lists of internally disjoint closed intervals into one sorted, disjoint list, joining overlapping or endpoint-touching intervals, in linear time.

Combine Two Ordered Schedules into One Gap-Free Timeline

You are given two lists of closed integer intervals, first and second. Each interval is a pair [start, end] that covers every point from start to end, endpoints included.

Inside each list the intervals are sorted by start in ascending order, and no two intervals in the same list overlap or share an endpoint. For example, in first, first[i][1] < first[i+1][0] always holds.

Build and return the union of the two lists as a single list of closed intervals. The result must satisfy:

  • It is sorted in ascending order.
  • Its intervals are pairwise disjoint, with no overlap and no shared endpoints.
  • The set of points it covers is exactly the set of points covered by at least one interval from either input.

Two intervals that overlap, or that share exactly one endpoint (such as [1, 4] and [4, 6]), must be fused into one interval ([1, 6]). Intervals that merely sit next to each other on the integer line without sharing a point (such as [1, 3] and [4, 5]) are not fused.

Aim for O(n + m) time, where n and m are the lengths of the two lists. Sorting the concatenation of both lists is not the intended approach.

Function

Implement merge_schedules(first, second), returning the list of merged intervals. If both inputs are empty, return an empty list.

Constraints

  • 0 <= len(first), len(second) <= 10^5
  • Every interval has exactly two integers: [start, end].
  • -10^9 <= start <= end <= 10^9
  • Within each list, intervals are sorted by start and do not overlap or touch one another.
  • Either list, or both, may be empty.

Examples

Example 1

Input: merge_schedules([[1, 3], [6, 9]], [[2, 5], [10, 12]])

Output: [[1, 5], [6, 9], [10, 12]]

Example 2

Input: merge_schedules([[1, 4], [8, 10]], [[4, 6], [7, 8]])

Output: [[1, 6], [7, 10]]

Hints

Hint 1

Both lists are already sorted by start, so you can walk through them with two pointers, always taking the interval with the smaller start, just like the merge step of merge sort.

Hint 2

While walking, maintain one 'open' interval. If the next interval's start is less than or equal to the open interval's end, extend the end using max; otherwise the open interval is finished and you can output it.

Hint 3

Use a sentinel such as None for 'no open interval' instead of 0, since coordinates may be negative. Remember to output the last open interval after the loop.