#1604
Alert Using Same Key-Card Three or More Times in a One Hour Period
MediumArrayHash TableStringSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution leverages sorting and a sliding window technique to efficiently check for key-card usage within a one-hour period. By sorting the times and using two pointers, we can quickly determine if three usages fall within the required time frame.
⚙️
Algorithm
3 steps- 1Step 1: Create a dictionary to group times by worker names.
- 2Step 2: For each worker, sort their usage times.
- 3Step 3: Use a sliding window approach to check if there are three usages within any one-hour period.
solution.py16 lines
1def alertNames(keyName, keyTime):
2 from collections import defaultdict
3 times = defaultdict(list)
4 for name, time in zip(keyName, keyTime):
5 times[name].append(time)
6 alerts = set()
7 for name, time_list in times.items():
8 time_list.sort()
9 n = len(time_list)
10 for i in range(n):
11 j = i
12 while j < n and (int(time_list[j][:2]) - int(time_list[i][:2])) * 60 + (int(time_list[j][3:]) - int(time_list[i][3:])) <= 60:
13 j += 1
14 if j - i >= 3:
15 alerts.add(name)
16 return sorted(alerts)ℹ
Complexity note: The time complexity is O(n log n) due to sorting the times for each worker. The space complexity is O(n) because we store the times in a dictionary and the alerts in a set.
- 1Sorting the times allows for efficient checking of time ranges using a sliding window.
- 2Using a set to store alerts ensures unique names without duplicates.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.