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

1
/**
2
* @param {string[]} keyName
3
* @param {string[]} keyTime
4
* @return {string[]}
5
*/
6
var alertNames = function (keyName, keyTime) {
7
// so we don't keep duplicates
8
const abusers = new Set();
9
// map: name->times[] (sorted)
10
const times = {};
11
for (let i = 0; i < keyName.length; i++) {
12
const name = keyName[i];
13
const time = keyTime[i];
14
if (times[name] == null) times[name] = [];
15
times[name].push(time);
16

17
if (times[name].length > 2) {
18
times[name].sort();
19
const len = times[name].length;
20
// we check all triples for a time difference below 1 hour.
21
// as times are sorted, we need to check all i and i+2
22
for (let i = 0; i < len - 2; i++) {
23
if (belowHour(times[name][i], times[name][i + 2])) {
24
abusers.add(name);
25
}
26
}
27
}
28
}
29
const ar = Array.from(abusers);
30
// sort them lexicographically
31
ar.sort();
32
return ar;
33

34
/*
35
same hour: true
36
hour diff is above 1: false
37
hour diff is 1: m2 must be <= m1
38
*/
39
function belowHour(t1, t2) {
40
const [h1, m1] = t1.split(":").map((num) => parseInt(num));
41
const [h2, m2] = t2.split(":").map((num) => parseInt(num));
42
if (h1 === h2) return true;
43
if (h2 - h1 > 1) return false;
44
if (m2 <= m1) return true;
45
}
46
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0