Windows (14, 16), (1, 3), (8, 10), (2, 6), (15, 18), (9, 12) and (3, 5), merged where they overlap. How many are left?
Pick one to see what it prints.
Here are the windows in sorted order, on a line of hours:
The windows in sorted order
(1, 3)
(2, 6)
(3, 5)
(8, 10)
(9, 12)
(14, 16)
(15, 18)
merged
merged
merged
068121418
hours
Sorted by start, each window either reaches the merged window just before it or starts a new one. So one pass after the sort does it: O(n log n) in all.
Two rules make the pass right:
Sort by start first. In arrival order, (1, 3) comes after (14, 16). 1 is at most 16, so it looks like an overlap, and everything merges into one window, 14 to 18.
Keep the larger end. When a window overlaps the merged one, the merged window ends at the later of the two ends, not at the new window's end. (3, 5) sits inside (1, 6). Take its end and (1, 6) shrinks to (1, 5).
In the editor, write merge(windows), the function the code above calls. It merges the seven maintenance windows.
Pick an answer above to see the rest
Instructions
1
Write merge(windows): merge the (start, end) windows that overlap or touch, and return them as [start, end] lists in order.
2
Sort by start first, so each window can only overlap the merged window just before it.