Combine Two Ordered Schedules into One Gap-Free Timeline
Greedy & IntervalsAuto-graded · 22 test casesLast 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat this as the merge step of merge sort followed by the standard "merge overlapping intervals" sweep, done in a single pass.
- Keep one pointer in each list. At each step, take the interval with the smaller start (ties can go to either list). This yields all intervals in non-decreasing order of start without sorting.
- Keep one "open" interval
[cur_start, cur_end], initially none.- If there is no open interval, the taken interval becomes the open one.
- If the taken interval's
start <= cur_end, it overlaps or touches the open interval, so setcur_end = max(cur_end, end). Themaxmatters when the taken interval is fully contained in the open one. - Otherwise there is a real gap: output the open interval and open a new one with the taken interval.
- After both lists are exhausted, output the open interval if one exists.
The comparison uses <= rather than <, so intervals sharing an endpoint are fused. It does not use <= cur_end + 1, so [1, 3] and [4, 5] stay separate.
Why it is correct
- Intervals are processed in non-decreasing start order, because each list is sorted and we always take the smaller head.
- The open interval always equals the union of a contiguous group of the intervals processed so far.
- When a taken interval has
start > cur_end, every unprocessed interval starts at or afterstart, which is strictly pastcur_end. No later interval can overlap or touch the open interval, so it is final and can be output. - Output intervals are separated by strict gaps and emitted in increasing order, so the result is sorted and pairwise disjoint. Every input point is covered and nothing extra is added, so the result is exactly the union.
Edge cases
- Empty lists: the loop simply uses whichever list still has items; if both are empty, the result is
[]. - Containment, identical intervals in both lists, single-point intervals, and chains that bridge intervals from alternating lists are all handled by the
<=check andmax. - Negative coordinates are safe because
Noneis used as the "no open interval" marker.
Complexity
- Time:
O(n + m), since each iteration advances exactly one pointer with constant work. - Space:
O(1)auxiliary beyond the output, which holds at mostn + mintervals.
Reference solution
from typing import List
def merge_schedules(first: List[List[int]], second: List[List[int]]) -> List[List[int]]:
result = []
i = j = 0
cur_start = cur_end = None
while i < len(first) or j < len(second):
if j >= len(second) or (i < len(first) and first[i][0] <= second[j][0]):
start, end = first[i]
i += 1
else:
start, end = second[j]
j += 1
if cur_start is None:
cur_start, cur_end = start, end
elif start <= cur_end:
cur_end = max(cur_end, end)
else:
result.append([cur_start, cur_end])
cur_start, cur_end = start, end
if cur_start is not None:
result.append([cur_start, cur_end])
return result