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

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


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> 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.

Step by Step Implementation For Alert Using Same Key Card Three Or More Times In A One Hour Period

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public boolean alertUsingSameKeyCardThreeOrMoreTimesInAOneHourPeriod(int[] keyTimes) {
        Map map = new HashMap<>();
        for (int i = 0; i < keyTimes.length; i++) {
            int key = keyTimes[i] % 100;
            if (!map.containsKey(key)) {
                map.put(key, 1);
            } else {
                map.put(key, map.get(key) + 1);
        for (Map.Entry entry : map.entrySet()) {
            if (entry.getValue() >= 3) {
                return true;
        return false;
def alert(key_times):
  # Initialize a dict to keep track of the number of times each key has been used
  key_count = {}
  # Loop through the key times
  for time in key_times:
    # If the key has been used less than 3 times, increment the count
    if time[0] in key_count and key_count[time[0]] < 3:
      key_count[time[0]] += 1
    # Otherwise, reset the count
      key_count[time[0]] = 1
  # Initialize a variable to keep track of whether an alert should be sent
  alert = False
  # Loop through the dict
  for key, val in key_count.items():
    # If the value is greater than or equal to 3, set the alert variable to True
    if val >= 3:
      alert = True
  # Return the alert variable
  return alert
// Solution:

// We can use a hash map to keep track of the number of times each key card is used in an hour.

// If a key card is used more than three times in an hour, we can output an alert.

var keyCards = {};

function checkForAlert(key) {

if(keyCards[key] === undefined) {

keyCards[key] = 1;

} else {



if(keyCards[key] >= 3) {

console.log("Alert! Key card used more than three times in an hour.");


if (cards.size() <= 2) return false;
        int count = 1;
        for (int i = 1; i < cards.size(); i++) {
            if (cards[i] == cards[i-1]) {
                if (count >= 3) return true;
            } else {
                count = 1;
        return false;
using System;
using System.Collections.Generic;

public class Solution {
    public IList AlertNames(string[] keyName, string[] keyTime) {
        // create a dictionary to store the names and times
        Dictionary> dict = new Dictionary>();
        // loop through the arrays and add the data to the dictionary
        for(int i = 0; i < keyName.Length; i++)
            // if the name is not in the dictionary, add it
                dict.Add(keyName[i], new List());
            // add the time to the list for the name
        // create a list to store the results
        List result = new List();
        // loop through the dictionary
        foreach(var kvp in dict)
            // sort the list of times
            // loop through the list of times
            for(int i = 0; i < kvp.Value.Count - 2; i++)
                // parse the current time and the next two times
                DateTime currTime = DateTime.Parse(kvp.Value[i]);
                DateTime nextTime = DateTime.Parse(kvp.Value[i + 1]);
                DateTime nextNextTime = DateTime.Parse(kvp.Value[i + 2]);
                // check if the difference between the current time and the next two times is less than or equal to one hour
                if((nextTime - currTime).TotalMinutes <= 60 && (nextNextTime - currTime).TotalMinutes <= 60)
                    // if so, add the name to the result list
                    // break out of the loop since we only need to add the name once
        // return the list of results
        return result;

Scroll to Top

Top 100 Leetcode Practice Problems In Java

Get 30% Off Instantly!
[gravityforms id="5" description="false" titla="false" ajax="true"]