Taro Logo

Reschedule Meetings for Maximum Free Time I

#1 Most AskedMedium
3 views
Topics:
ArraysSliding WindowsGreedy Algorithms

You are given an integer eventTime denoting the duration of an event, where the event occurs from time t = 0 to time t = eventTime.

You are also given two integer arrays startTime and endTime, each of length n. These represent the start and end time of n non-overlapping meetings, where the ith meeting occurs during the time [startTime[i], endTime[i]].

You can reschedule at most k meetings by moving their start time while maintaining the same duration, to maximize the longest continuous period of free time during the event.

The relative order of all the meetings should stay the same and they should remain non-overlapping.

Return the maximum amount of free time possible after rearranging the meetings.

Note that the meetings can not be rescheduled to a time outside the event.

Example 1:

Input: eventTime = 5, k = 1, startTime = [1,3], endTime = [2,5]

Output: 2

Explanation:

Reschedule the meeting at [1, 2] to [2, 3], leaving no meetings during the time [0, 2].

Example 2:

Input: eventTime = 10, k = 1, startTime = [0,2,9], endTime = [1,4,10]

Output: 6

Explanation:

Reschedule the meeting at [2, 4] to [1, 3], leaving no meetings during the time [3, 9].

Example 3:

Input: eventTime = 5, k = 2, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]

Output: 0

Explanation:

There is no time during the event not occupied by meetings.

Constraints:

  • 1 <= eventTime <= 109
  • n == startTime.length == endTime.length
  • 2 <= n <= 105
  • 1 <= k <= n
  • 0 <= startTime[i] < endTime[i] <= eventTime
  • endTime[i] <= startTime[i + 1] where i lies in the range [0, n - 2].

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. Are the input `startTime` and `endTime` arrays guaranteed to be sorted by start time, or should I sort them first?
  2. Can meetings overlap in the initial schedule, or are they guaranteed to be non-overlapping?
  3. When we "reschedule" a meeting by shifting it, can we change its relative order with other meetings, or do they have to maintain their original chronological order?
  4. If $k$ is greater than or equal to the total number of meetings, does that mean we can effectively clear the entire schedule except for the constraints, or is $k$ capped at the array length?
  5. Can meetings start at time `0` or end precisely at `eventTime`, and are there any minimum durations or constraints on the gaps between meetings?

Brute Force Solution

Approach

Imagine you have a calendar full of meetings and you are allowed to shift a certain number of them around to create the longest possible stretch of uninterrupted free time. The brute force strategy works by systematically trying every single combination of moving different meetings to different time slots and measuring the resulting gaps.

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

  1. Look at your entire schedule from start to finish, noting every meeting and every existing gap of free time between them.
  2. Pick a group of meetings up to the maximum number you are allowed to move.
  3. Imagine sliding this chosen group of meetings earlier or later in the day, bumping them right up against other meetings or the start and end of the workday.
  4. Measure how large the gaps of free time become after moving those meetings around.
  5. Write down the size of the biggest free time gap resulting from this specific arrangement.
  6. Reset the schedule back to normal, and then repeat this entire process for every other possible combination of moving different meetings.
  7. Compare the biggest gaps you found from all the different attempts, and select the overall largest one as your final answer.

Code Implementation

def max_free_time(event_duration, workday_limit, meeting_starts, meeting_ends):
    
    # Generate all combinations of meetings to evaluate every possible rescheduling permutation
    from itertools import combinations
    
    maximum_free_gap = 0
    total_meetings = len(meeting_starts)
    
    for moving_count in range(min(event_duration, total_meetings) + 1):
        for chosen_indices in combinations(range(total_meetings), moving_count):
            
            # Reconstruct the schedule by removing chosen meetings and compressing the remaining ones
            remaining_starts = [meeting_starts[index] for index in range(total_meetings) if index not in chosen_indices]
            remaining_ends = [meeting_ends[index] for index in range(total_meetings) if index not in chosen_indices]
            
            current_position = 0
            merged_intervals = []
            for start_time, end_time in zip(remaining_starts, remaining_ends):
                duration = end_time - start_time
                merged_intervals.append((current_position, current_position + duration))
                current_position += duration
                
            # Calculate all gaps in the newly formed schedule to find the maximum uninterrupted time
            all_gaps = []
            previous_end = 0
            for interval_start, interval_end in merged_intervals:
                all_gaps.append(interval_start - previous_end)
                previous_end = interval_end
            all_gaps.append(workday_limit - previous_end)
            
            if all_gaps:
                maximum_free_gap = max(maximum_free_gap, max(all_gaps))
                
    return maximum_free_gap

Big(O) Analysis

Time Complexity
O(n^k) – The brute force strategy systematically generates and tests every possible combination of moving up to k meetings out of n total meetings. For each of the O(n^k) subsets of meetings we choose to move, we iterate through the entire schedule of length n to measure all the resulting free time gaps. This requires nested operations where we evaluate roughly n^k combinations, each taking linear time proportional to n. Multiplying the subset combinations by the measurement cost leads to approximately n^k * n operations, which simplifies to O(n^(k+1)) or O(n^n) if k scales with n.
Space Complexity
O(1) – The brute force strategy described involves iterating through all combinations of meeting shifts using only a few primitive variables to track loop indices and maximum gap sizes. No auxiliary data structures, temporary lists, or recursive call stacks are utilized during the process. Because the memory required to maintain these tracking variables remains constant regardless of the number of meetings, the auxiliary space complexity is strictly O(1).

Optimal Solution

Approach

Instead of testing every possible way to move meetings, the optimal approach focuses on finding the longest continuous stretch of free time you can create by shifting a set number of meetings together. It uses a sliding window technique to evaluate groups of adjacent gaps efficiently.

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

  1. First, list out all the gaps of free time between your meetings, starting from the very beginning of the day until the end.
  2. Imagine grouping a specific number of these free time gaps together, separated by the meetings you are allowed to move.
  3. Calculate the total amount of free time inside this current group by adding up the gaps and the durations of the meetings sitting between them.
  4. Slide this group one meeting to the right by dropping the oldest gap and adding the next available gap on the right.
  5. Keep track of the largest total free time you encounter as you slide across the entire schedule.
  6. By checking every possible window of that specific size without starting over from scratch each time, you quickly find the absolute maximum free time possible.

Code Implementation

def max_free_time(event_horizon, meeting_start_times, meeting_end_times):
    # Collect all free time intervals including boundaries before and after all meetings.
    free_time_gaps = [meeting_start_times[0]]

    for meeting_index in range(1, len(meeting_start_times)):
        current_gap = meeting_start_times[meeting_index] - meeting_end_times[meeting_index - 1]
        free_time_gaps.append(current_gap)

    free_time_gaps.append(event_horizon - meeting_end_times[-1])

    window_size = event_limit + 1

    # Sum the initial window of gaps and the meetings that fall between them.
    current_window_sum = sum(free_time_gaps[:window_size])

    maximum_free_time = current_window_sum

    # Slide the window across all gaps to evaluate different merge combinations efficiently.
    for gap_index in range(window_size, len(free_time_gaps)):
        current_window_sum += free_time_gaps[gap_index] - free_time_gaps[gap_index - window_size]

        if current_window_sum > maximum_free_time:
            maximum_free_time = current_window_sum

    return maximum_free_time

Big(O) Analysis

Time Complexity
O(n) – To evaluate the schedule, we first iterate through the meetings array once to calculate all the individual free time gaps, taking linear time. Next, we use a sliding window approach that traverses the array of gaps a single time to find the maximum combined free time for the allowed number of moves. Since each gap enters and leaves the sliding window at most once, the total operations scale linearly with the number of meetings, n. This results in approximately 2n operations, which simplifies to O(n).
Space Complexity
O(N) – To implement the sliding window technique described in the steps, we must first construct an explicit array of free time gaps between the meetings, where N represents the number of meetings. This array scales linearly with the number of meetings, taking up extra memory proportional to N. Aside from this primary gap array, only a few primitive scalar variables are used to track indices and running sums, which require constant auxiliary space. Therefore, the total extra memory is dominated by the gap array, resulting in a space complexity of O(N).

Edge Cases

k is greater than or equal to the total number of meetings
How to Handle:
The entire event time becomes a single continuous free block since all meetings can be shifted out of the way.
k equals 0, meaning no meetings can be rescheduled
How to Handle:
The algorithm simply finds the maximum gap between the already fixed meetings and the boundaries.
Meetings already span the entire event time with zero free space initially
How to Handle:
Shifting meetings allows consolidating free spaces if k is greater than zero, or returns zero if k is zero.
All meetings are packed consecutively with no gaps between them
How to Handle:
Rescheduling a window of k meetings creates a large free block by shifting them to either end of the timeline.
Large scale inputs with maximum possible constraints on eventTime and meeting counts
How to Handle:
A sliding window approach running in O(n) time ensures efficient processing without exceeding time limits.
Time values exceed standard 32-bit integer limits
How to Handle:
Using 64-bit integers for all time calculations prevents potential overflow issues during subtractions.
Unsorted start and end time arrays
How to Handle:
The algorithm must initially sort the meetings by start time to accurately compute existing gaps.
0/2 completed