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:

  1. 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).
  2. 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 timestamp t finishes right as another booking starting at t begins; they do not conflict and can share one room.
  • No valid bookings: if intervals is empty or every pair has start >= 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 >= end may appear in intervals and must be ignored.
  • Target time complexity: O(N log N), where N = len(intervals).
  • Target auxiliary space complexity: O(N).

Step-by-step walkthrough

  1. Understand the problem and half-open intervals

    Each booking (start, end) is a half-open interval [start, end), meaning it includes start and stops right before end. 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 reaches 6.

    We need to return (total_covered_duration, min_rooms_required):

    1. 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.
    2. 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 at 4 right 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 rooms
    
  2. Why checking every unit of time is too slow

    Because all endpoints are integers, we could locate the earliest start and latest end, step through every 1-unit slot [t, t + 1), and count how many bookings satisfy start <= t < end. Every slot with count >= 1 adds 1 to 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) has n = 1, yet checking every unit of time would loop a billion times! Nothing changes in the middle of a booking—state only changes at the 2n start and end timestamps. Sorting lets us jump directly from endpoint to endpoint in O(n log n) time.

  3. 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 length 3 - 8 = -5 and 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 by start time so overlapping windows sit side by side from left to right. Unpacking for 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)
    
  4. 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 at start or later, nothing later can bridge the gap back to current_end. We bank current_end - current_start into total_duration and begin a fresh block [start, end).
    • Overlap or touch (start <= current_end): The new booking continues the busy span. We advance current_end only when end > current_end. Why check elif end > current_end? In Example 1, [5, 7) sits completely inside [4, 9) — blindly assigning current_end = end would shrink current_end from 9 down to 7!

    After the loop finishes, we add current_end - current_start one 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 = 10
    
    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
    
  5. 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 all k existing rooms are already occupied at that start instant—meaning k + 1 bookings genuinely overlap right then. So you never need more rooms than the peak simultaneous count, and fewer rooms could never house those k + 1 concurrent bookings.

    To find that peak, we run an event sweep:

    1. Convert each valid booking [start, end) into two events: (start, +1) (one room occupied) and (end, -1) (one room vacated).
    2. Sort all 2n events.
    3. Scan the sorted events, adding each +1 or -1 to active_rooms and tracking the peak max_rooms.

    What happens when one booking ends at 4 and another starts at 4? At timestamp 4, 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
    
  6. 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 +1 had sorted before -1 at t = 4, active_rooms would have spiked 1 -> 2 -> 1, wrongly reporting 2 rooms instead of 1.

  7. 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 at 4 <= 6 so we extend the block to [2, 9), and (5, 7) stays inside [2, 9). Next, (12, 15) starts at 12 > 9 (a gap), so we bank 9 - 2 = 7 units and open [12, 15), banking 15 - 12 = 3 at the end for 10 total 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 through 1, 2, 3, 2, 1, 0, 1, 0, hitting a peak of 3 rooms.

Complexity

Let n be the number of input intervals.

  • Time: O(n log n). Filtering invalid pairs takes one O(n) pass, sorting up to n valid windows and 2n endpoint events each takes O(n log n) comparisons, and both the merge pass and the event sweep perform O(1) arithmetic per item in O(n) time.
  • Space: O(n). We allocate up to n filtered (start, end) tuples and 2n (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 length 11, and because (4, -1) sorts ahead of (4, +1), they require just 1 room.
  • Multiple endings and starts at one timestamp: Every -1 event at timestamp t executes before any +1 event at t, releasing all vacated rooms before incoming bookings claim them.
  • Nested windows like [5, 7) inside [4, 9): Contribute 0 additional union length (the outer end 9 is 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 0 and ends as 1 in (time, kind) runs starts before ends at t = 4, falsely charging [0, 4) and [4, 10) 2 rooms instead of 1.
  • Assigning current_end = end unconditionally: When [5, 7) follows [4, 9), overwriting current_end = 7 forgets that the outer booking continues until 9; always retain max(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 > end pairs: An inverted pair like (8, 3) subtracts 5 from 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 need 1 room rather than 3.

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, push end, and track the maximum heap size in O(n log n) time.
  • Two-pointer sweep on separate start and end lists: Sort valid starts into one array and valid ends into another, advancing an index j into ends whenever ends[j] <= starts[i]; active rooms at starts[i] equals i - j + 1, running in O(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 t precisely when start <= t < end, meaning it started at or before t (start <= t) and has not yet ended by t (not end <= t). Sort all valid starts into one list and all valid ends into another once in O(n log n) time, then use binary search (repeatedly halving a sorted array to locate a boundary index in O(log n) comparisons) to count sessions with start <= t minus sessions with end <= t. Because every valid session satisfies start < end, any session with end <= t is guaranteed to also satisfy start <= t, so subtracting the two counts answers any query in O(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 for m stored intervals), alongside a running covered_sum. When [s, e) arrives (with s < e), locate all stored intervals that overlap or touch [s, e), subtract their lengths from covered_sum, remove them, and insert one fused interval [min_s, max_e) while adding its length. Even if a single wide arrival absorbs k stored intervals at once, every interval is inserted once and deleted at most once over the entire stream, yielding O(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 and O(n) auxiliary memory. When every timestamp lies inside a narrow integer range [lo, hi) of span R = hi - lo (for example, R = 1440 minutes in a day while n = 1,000,000), allocate a difference array (an array of length R + 1 initialized to zeros where each booking [start, end) adds +1 at start - lo and -1 at end - lo). Computing a prefix sum (a single left-to-right cumulative total across 0 .. R - 1) recovers the exact concurrent count in every minute, counting positive entries for union coverage and taking the maximum for peak rooms in O(n + R) time and O(R) memory without sorting.

Follow-up questions

Similar questions

More Flexport interview questions

All 5 Flexport questions →