[LeetCode] Alert Using Same Key-Card Three or More Times in a One Hour Period

1604. Alert Using Same Key-Card Three or More Times in a One Hour Period

LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker’s name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period.

You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person’s name and the time when their key-card was used in a single day.

Access times are given in the 24-hour time format “HH:MM”, such as “23:51” and “09:49”.

Return a list of unique worker names who received an alert for frequent keycard use. Sort the names in ascending order alphabetically.

Notice that “10:00” - “11:00” is considered to be within a one-hour period, while “22:51” - “23:52” is not considered to be within a one-hour period.

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
class Solution {
int parse(string time) {
auto p = time.find(':');
string hour = time.substr(0,p);
string minitue = time.substr(p + 1);
return stoi(hour) * 60 + stoi(minitue);
}
public:
vector<string> alertNames(vector<string>& keyName, vector<string>& keyTime) {
unordered_set<string> alert;
unordered_map<string, int> mp;
vector<pair<int, string>> key;
for(int i = 0; i < keyName.size(); i++) {
string name = keyName[i];
string time = keyTime[i];
int minute = parse(time);
key.push_back({minute, name});
}
sort(begin(key), end(key));

int l = 0, r = 0, n = key.size();
while(r < n) {
while(r < n and key[l].first + 60 >= key[r].first) {
if(++mp[key[r].second] == 3) alert.insert(key[r].second);
r++;
}
while(r < n and key[l].first + 60 < key[r].first) {
mp[key[l++].second]--;
}
}

vector<string> res(begin(alert), end(alert));
sort(begin(res), end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/17/PS/LeetCode/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.