Feature #2: Show Busy Schedule
Implementing the "Show Busy Schedule" feature for our "Google Calendar" project.
We'll cover the following...
Description
For the next feature, we want to find the times during which a user is busy. This feature is intended to show the busy hours of a user to other users without revealing the individual meeting slots. Therefore, if any meetings overlap or are back to back, then we want to merge their timings.
We will be provided a list of scheduled meetings, such as [[1, 4], [2, 5], [6, 8], [7, 9], [10, 13]]
. In this schedule, [1, 4]
and [2, 5]
, as well as [6, 8]
and [7, 9]
, are overlapping. After merging these meetings, the schedule becomes [[1, 5], [6, 9], [10, 13]]
.
The illustration below shows a visual representation of the example.
Note: For simplicity, we are mapping the military timing to integers in the input. So, for example,
8:00
will be denoted by8
in the code.
Solution
To solve this problem, it is best to sort the meetings based on the start_time
. Then, we can determine if two meetings should be merged or not by processing them simultaneously.
Here is how we’ll implement this feature:
- First, we will sort the meetings according to
start_time
. - Considering two meetings at a time, we will then check if the
start_time
of the second meeting is less than theend_time
of the first meeting. - If the condition is true, merge the meetings into a new meeting and delete the existing ones.
- Repeat the above steps until all the meetings are processed.
def merge_meetings(meeting_times)meeting_times.sort!merged = []meeting_times.each do |meeting|if (merged.length == 0 ) || (merged[merged.length-1][1] < meeting[0])merged.push(meeting)elsemerged[merged.length-1][1] = [merged[merged.length-1][1], meeting[1]].max()endendreturn mergedend# Driver codemeeting_times = [[1, 4], [2, 5], [6, 8], [7, 9], [10, 13]]p(merge_meetings(meeting_times))meeting_times = [[4, 7], [1, 3], [8, 10], [2, 3], [6, 8]]p(merge_meetings(meeting_times))
Complexity measures
Time complexity | Space complexity |
---|---|