LeetCode 2228: Users With Two Purchases Within Seven Days

Database

Problem Description

Explanation:

To solve this problem, we can iterate over the transactions and keep track of the user IDs along with their purchase timestamps. For each user, we maintain a list of timestamps in ascending order. Then, we iterate over each user's purchase timestamps to find if there are at least two purchases within seven days. :

Solutions

class Solution {
    public int numUsersWithTwoPurchasesWithinSevenDays(int[][] purchases) {
        Map<Integer, List<Integer>> userPurchases = new HashMap<>();
        int count = 0;
        
        for (int[] purchase : purchases) {
            int userId = purchase[0];
            int timestamp = purchase[1];
            
            userPurchases.putIfAbsent(userId, new ArrayList<>());
            userPurchases.get(userId).add(timestamp);
        }
        
        for (List<Integer> timestamps : userPurchases.values()) {
            if (timestamps.size() < 2) continue;
            
            Collections.sort(timestamps);
            for (int i = 0; i < timestamps.size() - 1; i++) {
                int j = i + 1;
                while (j < timestamps.size() && timestamps.get(j) - timestamps.get(i) <= 7) {
                    if (j - i >= 1) {
                        count++;
                        break;
                    }
                    j++;
                }
            }
        }
        
        return count;
    }
}

Loading editor...