Python coding

Overlap of two schedules

Two calendars, a and b, each list the closed ranges [start, end] when one person is free, with start <= end. Each list is sorted by start and its ranges are disjoint: no two share a point. Return every range where a range of a and a range of b overlap, sorted by start. Ranges that meet at one point share that point: [1, 3] and [3, 5] share [3, 3].

Either list may be empty. Aim for O(n + m), one pass over both lists.

Besides the tests, one large input (two lists of 2,800 ranges) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

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

Both lists are sorted, so walk them together with one index each, as when merging two sorted lists. Never compare every pair.

Hint 2

The overlap of a[i] and b[j] is [max(starts), min(ends)], and it exists only when that start is <= that end.

Hint 3

Then drop the range that ends first: it cannot overlap anything later in the other list. The one that ends later may still overlap the next range.

Solution and why it works
pythonO(n + m) · O(1) besides the output
def schedule_overlap(a: list[list[int]], b: list[list[int]]) -> list[list[int]]:
    out = []
    i = j = 0
    while i < len(a) and j < len(b):
        lo = max(a[i][0], b[j][0])
        hi = min(a[i][1], b[j][1])
        if lo <= hi:                         # closed ranges: one shared point counts
            out.append([lo, hi])
        if a[i][1] < b[j][1]:                # the range that ends first is done
            i += 1
        else:
            j += 1
    return out

Both lists are sorted, so two pointers suffice: the overlap of the current pair is [max(starts), min(ends)] when that start is <= that end. Then advance the range that ends first: every later range in the other list starts after its end, so it is finished. Each step drops one range: O(n + m). The trap is advancing the wrong pointer, or both: [1, 20] must stay to meet every short range in the other list.