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

Problem Description

Explanation:

To solve this problem, we can follow these steps:

  1. Create a map to store the keycard usage times for each worker.
  2. Sort the keycard usage times for each worker.
  3. Iterate over the sorted times for each worker and check if there are three consecutive times within a one-hour period.
  4. If such a pattern is found, add the worker to the result list.
  5. Sort the final result list and return it.

Time Complexity: O(n log n) where n is the total number of keycard usage times.

Space Complexity: O(n) for storing the keycard usage times.

:

Solutions

class Solution {
    public List<String> alertNames(String[] keyName, String[] keyTime) {
        Map<String, List<Integer>> map = new HashMap<>();
        List<String> result = new ArrayList<>();
        
        for (int i = 0; i < keyName.length; i++) {
            map.putIfAbsent(keyName[i], new ArrayList<>());
            map.get(keyName[i]).add(Integer.parseInt(keyTime[i].substring(0, 2)) * 60 + Integer.parseInt(keyTime[i].substring(3)));
        }
        
        for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
            List<Integer> times = entry.getValue();
            Collections.sort(times);
            for (int i = 2; i < times.size(); i++) {
                if (times.get(i) - times.get(i - 2) <= 60) {
                    result.add(entry.getKey());
                    break;
                }
            }
        }
        
        Collections.sort(result);
        return result;
    }
}

Loading editor...