LeetCode 2228: Users With Two Purchases Within Seven Days Solution
Master LeetCode problem 2228 (Users With Two Purchases Within Seven Days), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2228. Users With Two Purchases Within Seven Days
Problem Explanation
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. :
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2228 (Users With Two Purchases Within Seven Days)?
This page provides optimized solutions for LeetCode problem 2228 (Users With Two Purchases Within Seven Days) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2228 (Users With Two Purchases Within Seven Days)?
The time complexity for LeetCode 2228 (Users With Two Purchases Within Seven Days) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2228 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2228 in Java, C++, or Python.