Similar Problems

Similar Problems not available

Alert Using Same Key Card Three Or More Times In A One Hour Period - Leetcode Solution


LeetCode:  Alert Using Same Key Card Three Or More Times In A One Hour Period Leetcode Solution

Difficulty: Medium

Topics: string hash-table sorting array  


Design a system that triggers an alert if the same key card is used three or more times in a one-hour period. The system should reset its usage count after the one-hour period ends.


This problem can be solved using a HashMap that tracks the usage count of each key card. We will iterate over the logs one by one, maintaining a sliding window of log entries for the past one hour. If the usage count of a key card exceeds three, we will trigger an alert. We will also remove any log entries that are more than one hour old from the sliding window.

We can make the implementation more efficient by using a PriorityQueue to maintain a sorted list of log entries. We will insert each log entry into the PriorityQueue, and when we need to remove old entries, we will simply pop entries from the front until we find an entry that is less than one hour old.

Here is the Java code that implements the solution:

class AlertSystem { private HashMap<String, PriorityQueue<Integer>> cardUsage;

public AlertSystem() {
    cardUsage = new HashMap<>();

public void logEntry(String cardId, int time) {
    // Get the usage count for this cardId
    PriorityQueue<Integer> usageCount = cardUsage.getOrDefault(cardId, new PriorityQueue<>());

    // Remove any old log entries from the usage count
    while (!usageCount.isEmpty() && usageCount.peek() < time - 3600) {

    // Add the new log entry to the usage count

    // Update the card usage map
    cardUsage.put(cardId, usageCount);

    // Check if the alert should be triggered
    if (usageCount.size() >= 3) {
        System.out.println("ALERT: Card " + cardId + " used " + usageCount.size() + " times in the last hour!");


We can test our solution using the following code:

public static void main(String[] args) { AlertSystem alertSystem = new AlertSystem();

// Log some entries for card "A"
alertSystem.logEntry("A", 100);
alertSystem.logEntry("A", 200);
alertSystem.logEntry("A", 300);
alertSystem.logEntry("A", 400);
alertSystem.logEntry("A", 500);
alertSystem.logEntry("A", 600);

// Log some entries for card "B"
alertSystem.logEntry("B", 150);
alertSystem.logEntry("B", 250);
alertSystem.logEntry("B", 350);

// Log some entries for card "A" again (should trigger an alert)
alertSystem.logEntry("A", 700);
alertSystem.logEntry("A", 800);
alertSystem.logEntry("A", 900);

// Log some more entries for card "B" (should not trigger an alert)
alertSystem.logEntry("B", 450);
alertSystem.logEntry("B", 550);
alertSystem.logEntry("B", 650);


This should output:

ALERT: Card A used 3 times in the last hour!

This satisfies the requirements of the problem.

Alert Using Same Key Card Three Or More Times In A One Hour Period Solution Code