LeetCode 1511: Customer Order Frequency

Database

Problem Description

Explanation:

To solve this problem, we need to count the frequency of each customer's orders in the given order list. We can achieve this by using a HashMap to store the count of orders for each customer. Then, we can iterate through the order list and update the count for each customer.

Algorithm:

  1. Initialize a HashMap to store the count of orders for each customer.
  2. Iterate through the order list.
  3. For each order, check if the customer exists in the HashMap.
    • If the customer does not exist, add the customer to the HashMap with a count of 1.
    • If the customer exists, increment the count by 1.
  4. After iterating through all orders, return the HashMap containing the frequency of orders for each customer.

Time Complexity:

The time complexity of this approach is O(n), where n is the number of orders in the order list.

Space Complexity:

The space complexity of this approach is O(n) to store the counts for each customer.

:

Solutions

import java.util.*;

class Solution {
    public Map<String, Integer> countCustomerOrders(String[] orders) {
        Map<String, Integer> frequencyMap = new HashMap<>();
        
        for (String order : orders) {
            frequencyMap.put(order, frequencyMap.getOrDefault(order, 0) + 1);
        }
        
        return frequencyMap;
    }
}

Loading editor...