Python coding

Free time shared by everyone

Each person's calendar is a list of busy blocks [start, end] with start < end, sorted by start, and no two blocks of the same person overlap. Given schedules, one calendar per person, return the gaps [start, end] of positive length in which nobody is busy, sorted by start. Count only gaps between busy blocks: the open time before the first block and after the last one is not a gap. Blocks that meet at a point, like [1, 3] and [3, 5], leave no gap, even across people.

schedules may be empty, and so may any calendar. Make use of each calendar being sorted already.

Besides the tests, one large input (60 calendars, 3,000 blocks) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • shared_free_time([[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]) → [[5,6],[7,9]]
  • shared_free_time([[[1,2],[5,6]],[[1,3]],[[4,10]]]) → [[3,4]]
  • shared_free_time([[[1,3]],[[3,5]]]) → []
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Who is busy doesn't matter, only whether anyone is. Pool every block from every calendar and walk them in order of start.

Hint 2

Keep the latest end seen so far. A block that starts after it leaves a gap [latest_end, start]; otherwise extend with max, since a short block can sit inside a long one.

Hint 3

Each calendar is sorted already: heapq.merge(*schedules) yields every block in start order in O(N log k) for k calendars, without sorting everything.

Solution and why it works
pythonO(N log k), N blocks, k calendars · O(k) besides the output
import heapq


def shared_free_time(schedules: list[list[list[int]]]) -> list[list[int]]:
    free = []
    latest_end = None                        # when the current busy stretch ends
    for start, end in heapq.merge(*schedules):   # every block, in start order
        if latest_end is not None and start > latest_end:
            free.append([latest_end, start])
        latest_end = end if latest_end is None else max(latest_end, end)
    return free

Free time for everyone is what the union of all busy blocks leaves uncovered, so who is busy doesn't matter. Walk every block in start order, keeping the latest end: a start beyond it opens a gap, anything else extends it with max. heapq.merge uses the sorted calendars for O(N log k); sorting all blocks is O(N log N) and also fine. Traps: without max, [2, 3] inside [1, 10] invents a gap, and >= turns back-to-back blocks into empty gaps.