Statement▼
You are given a positive integer, days
, which represents the total number of days an employee is available for work, starting from day meetings
, where each entry meetings[i]
Your task is to count the days when the employee is available for work but has no scheduled meetings.
Note: The meetings may overlap.
Constraints:
1≤ days
≤100000 1≤ meetings.length
≤1000 meetings[i].length
==2 1≤ meetings[i][0]
≤ meetings[i][1]
≤ days
Solution
The core idea of this solution is to merge overlapping meetings into continuous intervals to efficiently track the occupied days. We begin by sorting the meetings to process them sequentially. As we iterate, we merge overlapping meetings while counting the occupied days whenever gaps appear. Finally, subtracting the total occupied days from the available days gives the number of free days.
Using the intuition above, we implement the algorithm as follows:
First, sort the
meetings
based on their start time to process them in order.Initialize a variable,
occupied
, with0 to count the days when the employee has scheduled meetings.Initialize two variables,
start
andend
, with the first meeting’s start and end times. These variables define the beginning and end of the merged meeting interval to efficiently track continuously occupied periods.Iterate through the remaining meetings:
If a meeting overlaps with the current merged meeting, extend the
end
time to merge it into the existing interval.Otherwise, add the days of the merged meeting to
occupied
asoccupied=occupied+(end−start+1) . Then, update thestart
andend
for the next interval.
After the loop, add the days of the last merged interval to
occupied
.Return the difference between
days
andoccupied
(days−occupied ), representing the number of days when the employee is available for work but has no scheduled meetings.
Let’s look at the following illustration to get a better understanding of the solution: