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


class Solution:
    def alertNames(self, keyName: list[str], keyTime: list[str]) -> list[str]:
        nameToMinutes = collections.defaultdict(list)

        for name, time in zip(keyName, keyTime):
            minutes = self._getMinutes(time)
            nameToMinutes[name].append(minutes)

        return sorted([name for name, minutes in nameToMinutes.items()
                       if self._hasAlert(minutes)])

    def _hasAlert(self, minutes: list[int]) -> bool:
        if len(minutes) > 70:
            return True
        minutes.sort()
        for i in range(2, len(minutes)):
            if minutes[i - 2] + 60 >= minutes[i]:
                return True
        return False

    def _getMinutes(self, time: str) -> int:
        h, m = map(int, time.split(':'))
        return 60 * h + m
    

Problem Description

Imagine you’re at a fancy hotel, and you see someone using their key card to enter their room. But wait! They swipe it not once, not twice, but three times in an hour! Is this a case of forgetfulness or a secret mission? The hotel staff is not amused and wants to know who this repeat offender is.

In this problem, you are tasked with identifying guests who have used their key card three or more times within a one-hour period. You’ll be given a list of names and corresponding times they used their key cards. Your job is to alert the hotel management about these suspicious activities.

Approach Explanation

The code works by first converting the time from a string format into minutes. It then groups the times by name using a dictionary. For each name, it checks if there are three or more entries within a one-hour window. If so, that name is flagged for alert.

Time and Space Complexity

  • Time Complexity: O(n log n), where n is the number of entries. This is due to the sorting step for each name’s time entries.
  • Space Complexity: O(n), as we store the times for each name in a dictionary.

Real-World Example

Picture this: You’re at a nightclub, and you see a guy named Bob who keeps swiping his key card to get back into the VIP area. Is he trying to impress someone, or is he just really bad at remembering where he left his drink? Either way, the bouncers are going to have a chat with him if he keeps this up!

Similar Problems

If you enjoyed this problem, you might also like these: