LeetCode 1596: The Most Frequently Ordered Products for Each Customer

Database

Problem Description

Explanation:

To solve this problem, we can iterate through the given order data and maintain a map to store the frequency of products ordered by each customer. We can then find the most frequently ordered products for each customer and return the result.

  1. Create a hashmap to store the frequency of products ordered by each customer.
  2. Iterate through the orders data and update the frequency of each product for each customer.
  3. For each customer, find the most frequently ordered products and store them in the result list.
  4. Return the result list.

Time Complexity: O(N), where N is the total number of orders. Space Complexity: O(N), for the hashmap and result list.

: :

Solutions

import java.util.*;

class Solution {
    public List<List<String>> mostFrequentProducts(List<List<String>> orders) {
        Map<String, Map<String, Integer>> freqMap = new HashMap<>();
        
        for (List<String> order : orders) {
            String customer = order.get(0);
            String product = order.get(1);
            
            if (!freqMap.containsKey(customer)) {
                freqMap.put(customer, new HashMap<>());
            }
            freqMap.get(customer).put(product, freqMap.get(customer).getOrDefault(product, 0) + 1);
        }
        
        List<List<String>> result = new ArrayList<>();
        
        for (String customer : freqMap.keySet()) {
            List<String> mostFrequent = new ArrayList<>();
            int maxFreq = 0;
            
            for (String product : freqMap.get(customer).keySet()) {
                int freq = freqMap.get(customer).get(product);
                if (freq > maxFreq) {
                    mostFrequent.clear();
                    mostFrequent.add(product);
                    maxFreq = freq;
                } else if (freq == maxFreq) {
                    mostFrequent.add(product);
                }
            }
            
            result.add(mostFrequent);
        }
        
        return result;
    }
}

Loading editor...