Total Busy Duration and Peak Concurrent Rooms
Hard · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Given a schedule of room bookings as integer pairs (start, end), where each booking occupies the half-open time window [start, end) (start inclusive, end exclusive), implement analyze_meetings(intervals) to compute two summary metrics:
total_covered_duration: the total length of time during which at least one valid booking is active (the measure of the union of all valid windows, counting overlapping stretches only once).min_rooms_required: the smallest number of conference rooms needed so every valid booking runs in its own room without time conflicts (equivalently, the peak number of valid bookings active at the same instant).
Interval Rules
- Invalid or empty windows: any pair with
start >= end(zero-duration or inverted endpoints) occupies no time and must be ignored. - Back-to-back bookings: because windows are half-open
[start, end), a booking ending at timestamptfinishes right as another booking starting attbegins; they do not conflict and can share one room. - No valid bookings: if
intervalsis empty or every pair hasstart >= end, return(0, 0).
def analyze_meetings(intervals: List[Tuple[int, int]]) -> Tuple[int, int]:
pass
Examples
Example 1
Input:
intervals = [(2, 6), (4, 9), (5, 7), (12, 15)]
Output:
(10, 3)
Explanation: [2, 6), [4, 9), and [5, 7) merge into one continuous busy span [2, 9) of length 7, and [12, 15) adds another 3 units for a total covered duration of 10. During [5, 6), all three bookings [2, 6), [4, 9), and [5, 7) are running simultaneously, requiring 3 rooms.
Example 2
Input:
intervals = [(0, 4), (4, 10), (10, 11)]
Output:
(11, 1)
Explanation: Together the three abutting bookings span [0, 11) continuously (11 total units), yet each booking vacates its room at the exact timestamp (4 and 10) when the next one starts, so 1 room handles the whole schedule.
Example 3
Input:
intervals = [(5, 5), (8, 3), (-2, -2)]
Output:
(0, 0)
Explanation: Every pair satisfies start >= end, leaving zero valid bookings, so both covered duration and required rooms equal 0.
Constraints
0 <= len(intervals) <= 10^5-10^9 <= start, end <= 10^9- Pairs with
start >= endmay appear inintervalsand must be ignored. - Target time complexity:
O(N log N), whereN = len(intervals). - Target auxiliary space complexity:
O(N).
Step-by-step walkthrough
Understand the problem and half-open intervals
Each booking
(start, end)is a half-open interval[start, end), meaning it includesstartand stops right beforeend. For example,[2, 6)occupies the four 1-unit slots[2, 3),[3, 4),[4, 5), and[5, 6), and vacates its room the instant the clock reaches6.We need to return
(total_covered_duration, min_rooms_required):- Total covered duration: the total length of time during which at least one valid booking is running. Units shared by multiple overlapping bookings still count only once.
- Minimum rooms required: the smallest number of rooms needed so every valid booking gets a room without conflicts. Back-to-back bookings like
[0, 4)and[4, 10)can share one room because the first finishes at4right as the second begins.
Time: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Booking A: [===============) Booking B: [===================) Booking C: [=======) Booking D: [===========) Covered: [===========================) [===========) -> (9 - 2) + (15 - 12) = 10 Active: 1 1 2 3 2 1 1 0 0 0 1 1 1 -> peak simultaneous = 3 roomsWhy checking every unit of time is too slow
Because all endpoints are integers, we could locate the earliest
startand latestend, step through every 1-unit slot[t, t + 1), and count how many bookings satisfystart <= t < end. Every slot with count>= 1adds1to the covered duration, and the largest count across all slots gives the room count.The catch is that runtime then depends on the clock span
R = max_end - min_start. A single booking(0, 1_000_000_000)hasn = 1, yet checking every unit of time would loop a billion times! Nothing changes in the middle of a booking—state only changes at the2nstart and end timestamps. Sorting lets us jump directly from endpoint to endpoint inO(n log n)time.Filter out invalid intervals and sort by start time
Before computing either metric, we discard pairs where
start >= end:- When
start == end(such as(5, 5)), the window has zero length and covers no time. - When
start > end(such as(8, 3)), keeping it would produce a negative length3 - 8 = -5and corrupt the coverage sum.
If no valid bookings remain (an empty input or Example 3), we return
(0, 0)immediately. Otherwise, we sort the valid(start, end)pairs bystarttime so overlapping windows sit side by side from left to right. Unpackingfor start, end in intervals:cleanly accepts both tuples(2, 6)and two-element lists[2, 6].def analyze_meetings(intervals: List[Tuple[int, int]]) -> Tuple[int, int]: # Phase 1: keep only positive-length intervals [start, end) where start < end. # valid_meetings: list of (start, end) tuples with start < end. valid_meetings: List[Tuple[int, int]] = [] for start, end in intervals: if start < end: valid_meetings.append((start, end)) if not valid_meetings: return (0, 0) # Phase 2: sort by start time so overlapping meetings sit next to each other. valid_meetings.sort() # Phase 3: compute union coverage and peak simultaneous room demand. covered = compute_covered_duration(valid_meetings) rooms = compute_peak_rooms(valid_meetings) return (covered, rooms)- When
Merge sorted intervals for total covered duration
Once valid bookings are sorted by
start, we compute the union length in one left-to-right pass by maintaining a single active busy block[current_start, current_end):- Gap (
start > current_end): Because all remaining bookings start atstartor later, nothing later can bridge the gap back tocurrent_end. We bankcurrent_end - current_startintototal_durationand begin a fresh block[start, end). - Overlap or touch (
start <= current_end): The new booking continues the busy span. We advancecurrent_endonly whenend > current_end. Why checkelif end > current_end? In Example 1,[5, 7)sits completely inside[4, 9)— blindly assigningcurrent_end = endwould shrinkcurrent_endfrom9down to7!
After the loop finishes, we add
current_end - current_startone final time to bank the last open block.Sorted bookings: [(2, 6), (4, 9), (5, 7), (12, 15)] Start with block [2, 6), total_duration = 0 Next (4, 9): 4 <= 6 (overlaps) and 9 > 6 -> extend block to [2, 9) Next (5, 7): 5 <= 9 (overlaps) and 7 <= 9 -> keep [2, 9) unchanged! Next (12, 15): 12 > 9 (gap!) -> add 9 - 2 = 7 to total_duration; new block [12, 15) End of loop: -> add 15 - 12 = 3 to total_duration; total = 10def compute_covered_duration(sorted_meetings: List[Tuple[int, int]]) -> int: """Return the total unique time covered by non-empty meetings sorted by start.""" total_duration = 0 # Track one active merged block [current_start, current_end) as we scan left to right. current_start, current_end = sorted_meetings[0] for start, end in sorted_meetings[1:]: if start > current_end: # Strict gap between current_end and start: close the finished block and start a new one. total_duration += current_end - current_start current_start = start current_end = end elif end > current_end: # Overlapping or touching meeting extends past current_end (nested shorter ones do not shrink it). current_end = end # Add the final open block after the loop finishes. total_duration += current_end - current_start return total_duration- Gap (
Sweep start and end events for minimum rooms
Why does the minimum number of rooms equal the maximum number of simultaneous bookings? Imagine handing out room keys chronologically as bookings start, always reusing a freed key first. You are forced to open a
(k + 1)-th room only when allkexisting rooms are already occupied at that start instant—meaningk + 1bookings genuinely overlap right then. So you never need more rooms than the peak simultaneous count, and fewer rooms could never house thosek + 1concurrent bookings.To find that peak, we run an event sweep:
- Convert each valid booking
[start, end)into two events:(start, +1)(one room occupied) and(end, -1)(one room vacated). - Sort all
2nevents. - Scan the sorted events, adding each
+1or-1toactive_roomsand tracking the peakmax_rooms.
What happens when one booking ends at
4and another starts at4? At timestamp4, our two events are(4, -1)and(4, +1). Python compares tuples element by element: timestamps tie (4 == 4), so it compares the delta (-1 < +1), placing(4, -1)before(4, +1). The outgoing booking frees its room before the incoming booking claims one!def compute_peak_rooms(valid_meetings: List[Tuple[int, int]]) -> int: """Return the maximum number of meetings active at the same instant.""" # events: list of (timestamp, room_delta) tuples; +1 when a meeting starts, -1 when it ends. events: List[Tuple[int, int]] = [] for start, end in valid_meetings: events.append((start, 1)) events.append((end, -1)) # Tuple sort orders by timestamp first, then room_delta: (t, -1) comes before (t, +1), # so meetings ending at time t free their rooms before meetings starting at time t take them. events.sort() active_rooms = 0 max_rooms = 0 for _, room_delta in events: active_rooms += room_delta if active_rooms > max_rooms: max_rooms = active_rooms return max_rooms- Convert each valid booking
Trace Example 1 and Example 2 end to end
Let's trace the event sweep on Examples 1 and 2 to see tie-breaking in action:
Example 1: [(2, 6), (4, 9), (5, 7), (12, 15)] Sorted events: (2,+1), (4,+1), (5,+1), (6,-1), (7,-1), (9,-1), (12,+1), (15,-1) active_rooms: 1 2 3 2 1 0 1 0 -> max_rooms = 3 Result: (10, 3) Example 2: [(0, 4), (4, 10), (10, 11)] Coverage merge: [0, 4), [4, 10), [10, 11) touch at 4 and 10 -> merges to [0, 11), length = 11 Sorted events: (0,+1), (4,-1), (4,+1), (10,-1), (10,+1), (11,-1) active_rooms: 1 0 1 0 1 0 -> max_rooms = 1 Result: (11, 1)Notice how in Example 2, if
+1had sorted before-1att = 4,active_roomswould have spiked1 -> 2 -> 1, wrongly reporting2rooms instead of1.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def compute_covered_duration(sorted_meetings: List[Tuple[int, int]]) -> int: """Return the total unique time covered by non-empty meetings sorted by start.""" total_duration = 0 # Track one active merged block [current_start, current_end) as we scan left to right. current_start, current_end = sorted_meetings[0] for start, end in sorted_meetings[1:]: if start > current_end: # Strict gap between current_end and start: close the finished block and start a new one. total_duration += current_end - current_start current_start = start current_end = end elif end > current_end: # Overlapping or touching meeting extends past current_end (nested shorter ones do not shrink it). current_end = end # Add the final open block after the loop finishes. total_duration += current_end - current_start return total_duration def compute_peak_rooms(valid_meetings: List[Tuple[int, int]]) -> int: """Return the maximum number of meetings active at the same instant.""" # events: list of (timestamp, room_delta) tuples; +1 when a meeting starts, -1 when it ends. events: List[Tuple[int, int]] = [] for start, end in valid_meetings: events.append((start, 1)) events.append((end, -1)) # Tuple sort orders by timestamp first, then room_delta: (t, -1) comes before (t, +1), # so meetings ending at time t free their rooms before meetings starting at time t take them. events.sort() active_rooms = 0 max_rooms = 0 for _, room_delta in events: active_rooms += room_delta if active_rooms > max_rooms: max_rooms = active_rooms return max_rooms def analyze_meetings(intervals: List[Tuple[int, int]]) -> Tuple[int, int]: # Phase 1: keep only positive-length intervals [start, end) where start < end. # valid_meetings: list of (start, end) tuples with start < end. valid_meetings: List[Tuple[int, int]] = [] for start, end in intervals: if start < end: valid_meetings.append((start, end)) if not valid_meetings: return (0, 0) # Phase 2: sort by start time so overlapping meetings sit next to each other. valid_meetings.sort() # Phase 3: compute union coverage and peak simultaneous room demand. covered = compute_covered_duration(valid_meetings) rooms = compute_peak_rooms(valid_meetings) return (covered, rooms)✅ Submit now — all tests should pass.
Intuition & how it works
Picture two everyday office tasks. First, to find how many total hours the conference floor is busy, imagine painting each booking onto a single timeline strip on the wall: overlapping paint strokes fuse into solid bars, and at the end you measure the lengths of those bars. Second, to find how many rooms you must build, imagine standing in the corridor with a clicker counter, clicking +1 whenever a session begins and -1 whenever one finishes—always letting the outgoing group vacate its room at 4:00 before the incoming 4:00 group walks in.
A naive strategy is to step through every 1-unit tick between the earliest start and latest end and count how many bookings cover each tick. That breaks down whenever timestamps span a wide range: a single booking (0, 1_000_000_000) would trigger a billion checks even though n = 1. Likewise, summing individual booking lengths double-counts overlapping hours.
Instead, we discard invalid windows where start >= end (since every booking is a half-open interval, an interval [start, end) that includes start and excludes end) and sort endpoints so we jump straight between transitions:
- Consider Example 1:
[(2, 6), (4, 9), (5, 7), (12, 15)]. - Coverage (interval merging): Starting from
[2, 6),(4, 9)starts at4 <= 6so we extend the block to[2, 9), and(5, 7)stays inside[2, 9). Next,(12, 15)starts at12 > 9(a gap), so we bank9 - 2 = 7units and open[12, 15), banking15 - 12 = 3at the end for10total covered units. - Rooms (sweep-line algorithm, a method that sorts start/end events by timestamp and scans across them with a running state): Sorted events are
(2,+1),(4,+1),(5,+1),(6,-1),(7,-1),(9,-1),(12,+1),(15,-1). Active rooms move through1, 2, 3, 2, 1, 0, 1, 0, hitting a peak of3rooms.
Complexity
Let n be the number of input intervals.
- Time:
O(n log n). Filtering invalid pairs takes oneO(n)pass, sorting up tonvalid windows and2nendpoint events each takesO(n log n)comparisons, and both the merge pass and the event sweep performO(1)arithmetic per item inO(n)time. - Space:
O(n). We allocate up tonfiltered(start, end)tuples and2n(timestamp, room_delta)event tuples.
Edge cases
- Empty list or all invalid pairs:
[]or[(5, 5), (8, 3), (-2, -2)]filters down to an empty list and returns(0, 0)right away. - Zero-length (
start == end) and inverted (start > end) windows: Discarded before sorting so they never add negative durations or distort room counts. - Back-to-back windows like
[0, 4),[4, 10), and[10, 11): Their union has length11, and because(4, -1)sorts ahead of(4, +1), they require just1room. - Multiple endings and starts at one timestamp: Every
-1event at timestamptexecutes before any+1event att, releasing all vacated rooms before incoming bookings claim them. - Nested windows like
[5, 7)inside[4, 9): Contribute0additional union length (the outer end9is retained), while still raising concurrent room demand during[5, 7). - Duplicate windows and negative timestamps: Identical bookings cover the union once while each demands its own room; negative integers sort and subtract identically to positive ones.
Common mistakes
- Sorting starts ahead of ends on timestamp ties: Encoding starts as
0and ends as1in(time, kind)runs starts before ends att = 4, falsely charging[0, 4)and[4, 10)2rooms instead of1. - Assigning
current_end = endunconditionally: When[5, 7)follows[4, 9), overwritingcurrent_end = 7forgets that the outer booking continues until9; always retainmax(current_end, end). - Forgetting to bank the final merged block after the loop: Because the loop only adds completed blocks when a gap appears, the last block must be added once the loop terminates.
- Retaining
start > endpairs: An inverted pair like(8, 3)subtracts5from the coverage total unless filtered out upfront. - Equating merged blocks with room count: Three abutting windows
[0, 4),[4, 10),[10, 11)merge into one continuous span[0, 11), yet need1room rather than3.
Alternative approaches
- Min-heap of active end times: A min-heap (a priority queue data structure providing
O(log n)access to the smallest stored value) can hold the end timestamps of active bookings while scanning sorted start times: before starting[start, end), pop every end time<= start, pushend, and track the maximum heap size inO(n log n)time. - Two-pointer sweep on separate start and end lists: Sort valid
startsinto one array and validendsinto another, advancing an indexjintoendswheneverends[j] <= starts[i]; active rooms atstarts[i]equalsi - j + 1, running inO(n log n)time without tuple events.
Follow-up questions
- Suppose callers repeatedly query how many sessions are active at an arbitrary timestamp t—how would you preprocess the schedule to answer each query quickly? A session occupies a room at timestamp
tprecisely whenstart <= t < end, meaning it started at or beforet(start <= t) and has not yet ended byt(notend <= t). Sort all validstartsinto one list and all validendsinto another once inO(n log n)time, then use binary search (repeatedly halving a sorted array to locate a boundary index inO(log n)comparisons) to count sessions withstart <= tminus sessions withend <= t. Because every valid session satisfiesstart < end, any session withend <= tis guaranteed to also satisfystart <= t, so subtracting the two counts answers any query inO(log n)time. - How could you maintain the running union coverage online if bookings arrive one by one in an unbounded stream instead of all at once? Store the disjoint merged intervals in sorted order inside a balanced binary search tree (a dynamic sorted tree where lookups, insertions, and deletions each run in
O(log m)time formstored intervals), alongside a runningcovered_sum. When[s, e)arrives (withs < e), locate all stored intervals that overlap or touch[s, e), subtract their lengths fromcovered_sum, remove them, and insert one fused interval[min_s, max_e)while adding its length. Even if a single wide arrival absorbskstored intervals at once, every interval is inserted once and deleted at most once over the entire stream, yieldingO(log n)amortized time (average cost per arrival across the full sequence). - How do the runtime and memory of the sorting approach scale, and how could you reduce both if every timestamp falls within a small fixed window like minutes of a single day? Sorting uses
O(n log n)time andO(n)auxiliary memory. When every timestamp lies inside a narrow integer range[lo, hi)of spanR = hi - lo(for example,R = 1440minutes in a day whilen = 1,000,000), allocate a difference array (an array of lengthR + 1initialized to zeros where each booking[start, end)adds+1atstart - loand-1atend - lo). Computing a prefix sum (a single left-to-right cumulative total across0 .. R - 1) recovers the exact concurrent count in every minute, counting positive entries for union coverage and taking the maximum for peak rooms inO(n + R)time andO(R)memory without sorting.
Follow-up questions
- Suppose callers repeatedly query how many sessions are active at an arbitrary timestamp t—how would you preprocess the schedule to answer each query quickly?
- How could you maintain the running union coverage online if bookings arrive one by one in an unbounded stream instead of all at once?
- How do the runtime and memory of the sorting approach scale, and how could you reduce both if every timestamp falls within a small fixed window like minutes of a single day?
Similar questions
- Select Minimax Word Guesses from Tile Feedback
- Maximize Non-Adjacent Totals on Lines and Trees
- Verify and Reconstruct IPv4 Strings
- Ocean Freight Container Packing Service with Hazmat Segregation
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger