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.
Note:"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.
💡 Note:daniel used keycard at 10:00, 10:40, 11:00 - the span is exactly 60 minutes (11:00 - 10:00), which triggers an alert. luis has times spread across 6 hours, no 3 accesses within 60 minutes.
Alert Using Same Key-Card Three or More Times in a One Hour Period — Solution
The key insight is to group access times by employee, then use sliding window on sorted times to efficiently detect violations. Best approach is Sort + Sliding Window: Time: O(n × k log k), Space: O(n × k) where n is number of employees and k is average accesses per employee.
Common Approaches
Approach
Time
Space
Notes
✓
Brute Force - Check All Combinations
O(n × k³)
O(n)
For each employee, check all possible 3-card combinations to see if any fit within 60 minutes
Sort + Sliding Window
O(n × k log k)
O(n × k)
Sort each employee's access times, then use sliding window to efficiently find 3+ accesses within 60 minutes
Brute Force - Check All Combinations — Algorithm Steps
Group keycard accesses by employee name
For each employee with 3+ accesses, check all combinations of 3 times
Convert time strings to minutes and check if max - min ≤ 60
Add employee to result if any combination violates the rule
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Group by Employee
Organize access times by worker name
2
Check Combinations
For each employee, test all 3-time combinations
3
Find Violations
Mark employees with any combination ≤ 60 minutes apart
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAMES 1000
#define MAX_NAME_LEN 50
#define MAX_TIMES 100
int timeToMinutes(char* time) {
int hours, minutes;
sscanf(time, "%d:%d", &hours, &minutes);
return hours * 60 + minutes;
}
int compare(const void* a, const void* b) {
return strcmp((char*)a, (char*)b);
}
int compareInts(const void* a, const void* b) {
return (*(int*)a) - (*(int*)b);
}
char** solution(char** keyName, char** keyTime, int keyNameSize, int* returnSize) {
char names[MAX_NAMES][MAX_NAME_LEN];
int times[MAX_NAMES][MAX_TIMES];
int counts[MAX_NAMES];
int numEmployees = 0;
// Group times by employee
for (int i = 0; i < keyNameSize; i++) {
int found = -1;
for (int j = 0; j < numEmployees; j++) {
if (strcmp(names[j], keyName[i]) == 0) {
found = j;
break;
}
}
if (found == -1) {
strcpy(names[numEmployees], keyName[i]);
times[numEmployees][0] = timeToMinutes(keyTime[i]);
counts[numEmployees] = 1;
numEmployees++;
} else {
times[found][counts[found]] = timeToMinutes(keyTime[i]);
counts[found]++;
}
}
char** result = malloc(MAX_NAMES * sizeof(char*));
int resultCount = 0;
// Check each employee
for (int emp = 0; emp < numEmployees; emp++) {
if (counts[emp] < 3) continue;
// Check all combinations of 3 times
int foundViolation = 0;
for (int i = 0; i < counts[emp] && !foundViolation; i++) {
for (int j = i + 1; j < counts[emp] && !foundViolation; j++) {
for (int k = j + 1; k < counts[emp]; k++) {
int threeTimes[3] = {times[emp][i], times[emp][j], times[emp][k]};
qsort(threeTimes, 3, sizeof(int), compareInts);
if (threeTimes[2] - threeTimes[0] <= 60) {
foundViolation = 1;
break;
}
}
}
}
if (foundViolation) {
result[resultCount] = malloc((strlen(names[emp]) + 1) * sizeof(char));
strcpy(result[resultCount], names[emp]);
resultCount++;
}
}
// Sort result
qsort(result, resultCount, sizeof(char*), compare);
*returnSize = resultCount;
return result;
}
int main() {
// Simple parsing for demonstration
char** keyName = malloc(MAX_NAMES * sizeof(char*));
char** keyTime = malloc(MAX_NAMES * sizeof(char*));
int size = 0;
// Read input (simplified)
char line[1000];
fgets(line, sizeof(line), stdin);
// Parse keyName array - implementation would parse JSON format
fgets(line, sizeof(line), stdin);
// Parse keyTime array - implementation would parse JSON format
int returnSize;
char** result = solution(keyName, keyTime, size, &returnSize);
printf("[");
for (int i = 0; i < returnSize; i++) {
printf("\"%s\"", result[i]);
if (i < returnSize - 1) printf(",");
}
printf("]\n");
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n × k³)
For each of n employees, we check C(k,3) combinations where k is number of accesses per employee
n
2n
✓ Linear Growth
Space Complexity
O(n)
Hash map to group accesses by employee name
n
2n
⚡ Linearithmic Space
12.5K Views
MediumFrequency
~25 minAvg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.