LeetCode 1565: Unique Orders and Customers Per Month
Problem Description
Explanation
To solve this problem, we need to count the unique orders and customers per month. We can achieve this by using hash sets to keep track of unique orders and customers for each month. We iterate through the input data and populate the sets accordingly. Finally, we return the count of unique orders and customers for each month.
Algorithm:
- Create a hash set for unique orders and a hash set for unique customers for each month.
- Iterate through the input data.
- For each record, add the order ID to the unique orders set and the customer ID to the unique customers set for that month.
- Return the count of unique orders and customers for each month.
Time Complexity:
The time complexity of this algorithm is O(n) where n is the number of records in the input data.
Space Complexity:
The space complexity of this algorithm is O(n) as we store unique orders and customers for each month.
Solutions
import java.util.*;
class Solution {
public List<List<Integer>> uniqueOrdersAndCustomersPerMonth(int[][] data) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < 12; i++) {
Set<Integer> uniqueOrders = new HashSet<>();
Set<Integer> uniqueCustomers = new HashSet<>();
for (int j = 0; j < data.length; j++) {
if (data[j][1] == i + 1) {
uniqueOrders.add(data[j][0]);
uniqueCustomers.add(data[j][2]);
}
}
List<Integer> monthStats = new ArrayList<>();
monthStats.add(uniqueOrders.size());
monthStats.add(uniqueCustomers.size());
result.add(monthStats);
}
return result;
}
}
Loading editor...