11/42
Part 3 of 8 · MergingLearn and do

Free time is the gaps, found with one number that only moves later

Take the same three calendars and a working day from 8 to 18. Merged, everyone's busy blocks are (9, 11) and (12, 17). So the free time is (8, 9), (11, 12) and (17, 18). That's Employee Free Time.

You don't need the merged list itself. Walk the blocks in start order and keep one number, free_from. Everything before it is busy or already reported.

  • A block that starts after free_from leaves a gap.
  • Every block pushes free_from out to its end, if its end is later.
Block, in start orderGap it leavesfree_from after it
8, the start of the day
(9, 10)(8, 9)10
(10, 11)11
(12, 13)(11, 12)13
(12, 15)15
(13, 14)15
(15, 16)16
(16, 17)17
the end of the day(17, 18)

Watch the row for (13, 14). Its end, 14, is earlier than free_from, so free_from stays at 15.

When each person's calendar already comes sorted, you don't need to sort them all together either. The heaps lesson's merge of k sorted streams, heapq.merge(ana, bo, cy), hands out the blocks in start order in O(N log k) for N blocks across k people.

One slip breaks the walk: setting free_from to the block's end instead of the later end. Then a block inside another drags free_from back:

Free time from 12 to 17, two ways
(12, 15)
(13, 14)
(15, 16)
free, with max
free, with end inside (12, 15)
free, with end
121314151617

In the editor, write the loop of free_time(busy, day_start, day_end): walk everyone's busy blocks in start order with free_from, and collect the gaps in gaps.