Alert Using Same Key-Card Three or More Times in a One Hour Period
The problem deals with finding the names of workers who used their key-card three or more times within a one-hour period. We need to group the access times for each worker and check for any three consecutive times that fall within a one-hour window.
Python solution:
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
| from collections import defaultdict
class Solution:
def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
# Function to convert time from "HH:MM" to minutes
def time_to_minutes(time: str) -> int:
h, m = map(int, time.split(":"))
return h * 60 + m
# Dictionary to store names and their corresponding time entries
name_times = defaultdict(list)
# Process the entries
for name, time in zip(keyName, keyTime):
name_times[name].append(time_to_minutes(time))
# Result to store the names that have alerts
result = []
# Check each name's time entries
for name, times in name_times.items():
times.sort() # Sort the times
for i in range(2, len(times)):
# Check if there are three times within a 60-minute window
if times[i] - times[i - 2] <= 60:
result.append(name)
break
return sorted(result)
|
The code first converts the times to minutes past midnight for easier comparison. Then, for each worker, it checks for three consecutive times within a 60-minute window. If found, it adds the name to the result. Finally, the result is sorted alphabetically as required by the problem statement.