[AlgoExpert] Calendar Matching

Calendar Matching

  • Time : O(n + m)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <vector>

using namespace std;

struct StringMeeting {
string start;
string end;
};

int toInteger(string time) {
size_t pos = time.find(':');
int hour = stoi(time.substr(0,pos));
int minute = stoi(time.substr(pos+1));
return hour * 60 + minute;
}

pair<int, int> toInteger(StringMeeting& meeting) {
return {toInteger(meeting.start), toInteger(meeting.end)};
}

string toTime(int time) {
int hour = time / 60;
int minute = time % 60;
string h = to_string(hour), m = to_string(minute);
if(m.length() == 1) m = "0" + m;
return h + ":" + m;
}

void insertIfValid(vector<StringMeeting>& res, int start, int end, int duration) {
if(start + duration <= end) {
res.push_back({toTime(start), toTime(end)});
}
}

vector<StringMeeting> calendarMatching(vector<StringMeeting> calendar1,
StringMeeting dailyBounds1,
vector<StringMeeting> calendar2,
StringMeeting dailyBounds2,
int meetingDuration) {
vector<StringMeeting> res;
int i = 0, j = 0, free = max(toInteger(dailyBounds1.start), toInteger(dailyBounds2.start)), n = calendar1.size(), m = calendar2.size();
while(i < n and j < m) {
auto [c1s, c1e] = toInteger(calendar1[i]);
auto [c2s, c2e] = toInteger(calendar2[j]);

insertIfValid(res, free, min(c1s, c2s), meetingDuration);

if(c1s > c2s) {
j++; free = max(free, c2e);
} else {
i++; free = max(free, c1e);
}
}

while(i < n) {
auto [c1s, c1e] = toInteger(calendar1[i++]);
insertIfValid(res, free, c1s, meetingDuration);
free = max(free, c1e);
}

while(j < m) {
auto [c2s, c2e] = toInteger(calendar2[j++]);
insertIfValid(res, free, c2s, meetingDuration);
free = max(free, c2e);
}

insertIfValid(res, free, min(toInteger(dailyBounds1.end), toInteger(dailyBounds2.end)), meetingDuration);

return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/calendar-matching/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.