LeetCode 2893: Calculate Orders Within Each Interval

Database

Problem Description

Explanation:

Given a list of orders with timestamps, we need to calculate the number of orders within each time interval.

To solve this problem, we can follow these steps:

  1. Create a TreeMap to store the count of orders for each timestamp.
  2. Iterate through the list of orders and update the count in the TreeMap.
  3. Calculate the cumulative count of orders for each timestamp interval.
  4. Return the list of counts for each interval.

Time Complexity: O(n log n) where n is the number of orders. Space Complexity: O(n) for the TreeMap. :

Solutions

import java.util.*;

class Solution {
    public List<Integer> countOrders(int[][] orders) {
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for (int[] order : orders) {
            map.put(order[0], map.getOrDefault(order[0], 0) + 1);
            map.put(order[1] + 1, map.getOrDefault(order[1] + 1, 0) - 1);
        }
        
        int count = 0;
        List<Integer> result = new ArrayList<>();
        for (int val : map.values()) {
            count += val;
            result.add(count);
        }
        
        return result;
    }
}

Loading editor...