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 startTime
. 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
startTime
. - Considering two meetings at a time, we will then check if the
startTime
of the second meeting is less than theendTime
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.
bool sortCol(const std::vector<int>& v1, const std::vector<int>& v2) {return v1[0] < v2[0];}void mergeMeetings(std::vector<std::vector<int>>& meetingTimes, std::vector<std::vector<int>>& merged){std::sort(meetingTimes.begin(), meetingTimes.end(), sortCol);for (auto meeting: meetingTimes){int size = merged.size();if(size == 0 || merged[size - 1][1] < meeting[0]){merged.push_back(meeting);}else{merged[size - 1][1] = std::max(merged[size - 1][1], meeting[1]);}}}// Driver codeint main() {std::vector<std::vector<int>> meetingTimes1 = {{1, 4}, {2, 5}, {6, 8}, {7, 9}, {10, 13}};std::vector<std::vector<int>> merged;// First set of meetingsmergeMeetings(meetingTimes1, merged);print(merged);merged.clear();// Second set of meetingsstd::vector<std::vector<int>> meetingTimes2 = {{4, 7}, {1, 3}, {8, 10}, {2, 3}, {6, 8}};mergeMeetings(meetingTimes2, merged);print(merged);}
Complexity measures
Time complexity | Space complexity |
---|---|