Problem
Given a list of calendar events for a day, build the Busy View: a list of consolidated time ranges that merge overlapping or adjacent events.
Each event has:
- start time (minute granularity)
- end time
- title (ignored for Busy View)
Example
Input events:
(100, 300, "Event")
(115, 145, "Event")
(145, 215, "Event")
(200, 400, "Event")
(215, 230, "Event")
(215, 415, "Event")
(600, 700, "Event")
(500, 600, "Event")
Output Busy View:
(100, 415)
(500, 700)
Approach
This is the classic merge intervals pattern:
- Sort events by start time.
- Sweep left-to-right and merge into the current interval if it overlaps/touches.
- Otherwise, close the current interval and start a new one.
Python
def busy_view(events: list[tuple[int, int, str]]) -> list[tuple[int, int]]:
if not events:
return []
events.sort(key=lambda x: x[0])
res = []
cur_s, cur_e = events[0][0], events[0][1]
for s, e, _ in events[1:]:
if s <= cur_e: # overlap or adjacent
cur_e = max(cur_e, e)
else:
res.append((cur_s, cur_e))
cur_s, cur_e = s, e
res.append((cur_s, cur_e))
return res
Complexity
- Time:
O(n log n)for sorting - Space:
O(n)for output
Need interview help? Contact OA VO Service
- 📧 Email: [email protected]
- 📱 Phone: +86 17863968105
Need real interview questions? Contact WeChat: Coding0201 to get the questions.