Taro Logo

Meeting Rooms II

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+39
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
3.1K views
Topics:
ArraysGreedy AlgorithmsDynamic Programming

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.

Example 1:

Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2

Example 2:

Input: intervals = [[7,10],[2,4]]
Output: 1

Constraints:

  • 1 <= intervals.length <= 104
  • 0 <= starti < endi <= 106

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the start and end times be represented as floating-point numbers, or should we assume they are always integers?
  2. Are meeting intervals inclusive or exclusive? For example, if one meeting ends at 10 and another starts at 10, do they overlap or can they share the same room?
  3. How should we handle an empty input array where no meetings are scheduled? Should it return 0 rooms?
  4. Can the start time of a meeting be greater than or equal to its end time, or is it guaranteed that start < end for every interval?
  5. Are the input intervals guaranteed to be pre-sorted by their start times, or should we expect them in arbitrary order?

Brute Force Solution

Approach

Imagine you have a list of meetings with different start and end times, and you need to figure out the minimum number of rooms required so that no meetings overlap. The brute force approach tries every possible way of assigning meetings to rooms and checks all combinations until you find the minimum number of rooms that actually works without any scheduling conflicts.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first meeting and assign it to the first room.
  2. Take the next meeting and check if it overlaps in time with any meeting already assigned to the first room.
  3. If it does not overlap, place it in that same room. If it does overlap, you are forced to open a new room and place the meeting there.
  4. Continue this process for every single meeting on your list, checking it against every existing room to see if it fits anywhere.
  5. If a meeting does not fit in any of the currently open rooms, create yet another new room for it.
  6. Keep track of the total number of rooms you ended up using for this specific trial.
  7. Now, imagine completely resetting the room assignments and trying a different combination or order of placing meetings, though in spirit the exhaustive method simply tests every logical grouping of overlapping times.
  8. Compare the room counts from all the different ways you could possibly group the meetings, and identify the absolute smallest number of rooms that successfully handled all the meetings without any time clashes.

Code Implementation

def min_meeting_rooms(meeting_intervals):
    # Sort intervals to evaluate meetings chronologically and test combinations systematically
    sorted_intervals = sorted(meeting_intervals, key=lambda meeting: meeting[0])

    room_allocation_list = []

    for current_meeting in sorted_intervals:
        room_found = False

        for assigned_room in room_allocation_list:
            # If the room's last meeting ends before current starts, we can reuse this room safely
            if assigned_room[-1][1] <= current_meeting[0]:
                assigned_room.append(current_meeting)

                room_found = True

                break

        # If no existing room is free, we must open a brand new room for this meeting
        if not room_found:
            room_allocation_list.append([current_meeting])

    # The total rooms needed equals the maximum number of rooms active during any trial
    return len(room_allocation_list)

Big(O) Analysis

Time Complexity
O(n²) – For each of the n meetings in the input list, the brute force approach checks it against every currently open room and existing meeting assignment to find a valid slot. As we process all n meetings and potentially compare each meeting against a growing number of active rooms and prior allocations in the worst-case scenario, we perform roughly n * n/2 pair-checking operations. Summing these checks across all meetings yields approximately n squared operations, which ultimately simplifies to Big O of n squared.
Space Complexity
O(n) – The brute force approach and standard optimal algorithms for this problem require storing and tracking meetings, where N is the total number of meetings. Specifically, sorting or managing the meeting intervals and maintaining tracking variables or priority queues for the active rooms requires storing up to N elements. As the number of meetings increases, these auxiliary data structures and tracking mechanisms scale in direct proportion to N, resulting in linear auxiliary space. Therefore, the extra memory used beyond the input itself simplifies to Big O of N.

Optimal Solution

Approach

To figure out how many meeting rooms are needed without wasting time checking every single overlap manually, the best strategy is to look at the meetings in chronological order and keep track of when rooms become free. By organizing the start and end times separately, we can simulate walking through the day and simply count how many rooms are occupied at the busiest moment.

Here's how the algorithm would work step-by-step:

  1. Gather all the meeting start times and line them up in the order they happen throughout the day.
  2. Gather all the meeting end times and line them up in the order they finish throughout the day.
  3. Start walking through the day from the very first meeting, keeping a running count of the rooms currently in use.
  4. Whenever a new meeting starts, you must assign it a room, which increases your count of busy rooms.
  5. Whenever a meeting finishes before or at the same time a new one begins, a room opens up, so you can decrease your count of busy rooms.
  6. Keep track of the highest number of rooms you ever had to use at the exact same time.
  7. Once you have checked every meeting from start to finish, that peak number you recorded is the total amount of rooms you need.

Code Implementation

def min_meeting_rooms(meeting_intervals):
    # Separating start and end times allows us to track timeline events chronologically.
    start_times = sorted([interval[0] for interval in meeting_intervals])
    end_times = sorted([interval[1] for interval in meeting_intervals])

    rooms_currently_used = 0
    peak_rooms_needed = 0
    start_pointer = 0
    end_pointer = 0
    total_meetings = len(meeting_intervals)

    while start_pointer < total_meetings:
        # If a meeting ends before or when the next starts, a room becomes immediately available.
        if start_times[start_pointer] >= end_times[end_pointer]:
            rooms_currently_used -= 1
            end_pointer += 1

        rooms_currently_used += 1
        start_pointer += 1

        # Tracking the maximum concurrent rooms ensures we allocate enough capacity for peak overlap.
        if rooms_currently_used > peak_rooms_needed:
            peak_rooms_needed = rooms_currently_used

    return peak_rooms_needed

Big(O) Analysis

Time Complexity
O(n log n) – The primary cost driving this algorithm is sorting the start and end times arrays, each containing n elements, which takes O(n log n) time. As we walk through the sorted start and end times using two pointers to track active rooms, we iterate through each of the 2n time points exactly once, taking linear O(n) time. Combining these phases yields roughly 2 * n log n plus 2n operations, where the logarithmic sorting term dominates as the input size scales. Therefore, the overall time complexity simplifies to O(n log n).
Space Complexity
O(N) – To implement the strategy of lining up the meeting times, we must create two separate auxiliary arrays to store the start times and the end times. Given that there are N meetings, the start times array holds N elements and the end times array also holds N elements. A few primitive variables are used to track the running count and the peak number of rooms, requiring a constant amount of extra memory. Therefore, the total auxiliary space complexity is driven entirely by these two lists, scaling linearly with the number of meetings N. This simplifies to Big O notation of O(N).

Edge Cases

Empty array of intervals
How to Handle:
Return zero rooms immediately since no meetings require a space.
Single meeting interval
How to Handle:
Return one room since exactly one interval always requires a single conference room.
Back-to-back meetings where one ends exactly when another starts
How to Handle:
Reuse the same room by checking if the earliest ending meeting time is less than or equal to the current meeting start time.
Completely overlapping meetings sharing the exact same start and end times
How to Handle:
Allocate separate rooms for each overlapping interval by tracking concurrent active meetings.
Meetings with negative time coordinates or zero-duration intervals
How to Handle:
Process them correctly by relying purely on numerical start and end comparisons during sorting.
Massive scale input with hundreds of thousands of intervals
How to Handle:
Maintain efficient O(n log n) time complexity using a min-heap or chronological sorting approach.
Inputs with extreme boundary integer values for start and end times
How to Handle:
Use standard 32-bit or 64-bit integer types natively supported by the language without causing arithmetic overflow.
0/75 completed