progress

~/problems / Intervals

Longest stretch with the shop open

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A corner shop is open whenever at least one employee is on shift. A shift (start, end) covers start up to but not including end. Shifts can overlap, and a shift starting exactly when another ends is a handover: the shop stays open.

Write longest_open(shifts: list[tuple[int, int]]) -> int: the length of the longest unbroken open stretch, or 0 with no shifts. Shifts are in no particular order.

longest_open([(540, 600), (720, 780), (590, 660)])   # 120   540..660, the 720..780 stretch is only 60
longest_open([(0, 10), (10, 20), (25, 30)])          # 20    handover at 10 keeps it open 0..20
longest_open([(5, 50), (10, 20)])                    # 45    a shift inside another adds nothing

Up to 10^5 shifts, times between -10^9 and 10^9.

⭐ Bonus: a speed test with 100,000 shifts earns a star in O(n log n).

Show hint

sort by start and sweep, keeping the current stretch's start and end. A shift with start <= end extends it; otherwise record the stretch and begin a new one.

Topic: Intervals / sweep line. Sort by start, merge; sweep events for overlaps.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc