Alert Using Same Key-Card Three or More Times in a One Hour Period — LeetCode 1604 Python Solution

MediumArrayHash TableStringSorting
Problem
#1604
Pattern
Sorting
Reading time
3 min

The problem

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.

Example

Input
keyName = ["daniel","daniel","daniel","luis","luis","luis","luis"], keyTime = ["10:00","10:40","11:00","09:00","11:00","13:00","15:00"]
Output
["daniel"]
Explanation
"daniel" used the keycard 3 times in a one-hour period ("10:00","10:40", "11:00").

Python solution

Python
class Solution:
    def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
        d = defaultdict(list)
        for name, t in zip(keyName, keyTime):
            t = int(t[:2]) * 60 + int(t[3:])
            d[name].append(t)
        ans = []
        for name, ts in d.items():
            if (n := len(ts)) > 2:
                ts.sort()
                for i in range(n - 2):
                    if ts[i + 2] - ts[i] <= 60:
                        ans.append(name)
                        break
        ans.sort()
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1604. Alert Using Same Key-Card Three or More Times in a One Hour Period is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1604. Alert Using Same Key-Card Three or More Times in a One Hour Period?
LeetCode 1604. Alert Using Same Key-Card Three or More Times in a One Hour Period is rated Medium on LeetCode.
What is the time complexity of LeetCode 1604. Alert Using Same Key-Card Three or More Times in a One Hour Period?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1604. Alert Using Same Key-Card Three or More Times in a One Hour Period?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1604. Alert Using Same Key-Card Three or More Times in a One Hour Period cover?
LeetCode 1604. Alert Using Same Key-Card Three or More Times in a One Hour Period is tagged Array, Hash Table, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview