#1327

List the Products Ordered in a Period

Easy
DatabaseHash MapAggregationJoin
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

In the optimal approach, we will use a single pass to aggregate the units ordered for each product in February 2020, which reduces the number of scans and improves efficiency.

⚙️

Algorithm

4 steps
  1. 1Step 1: Filter the Orders table for February 2020.
  2. 2Step 2: Use a HashMap to aggregate the total units ordered for each product_id.
  3. 3Step 3: Join the aggregated results with the Products table to get product names.
  4. 4Step 4: Filter the results to include only those products with a total unit count of at least 100.
solution.py7 lines
1SELECT p.product_name, total_units
2FROM (SELECT product_id, SUM(unit) AS total_units
3      FROM Orders
4      WHERE order_date >= '2020-02-01' AND order_date < '2020-03-01'
5      GROUP BY product_id
6      HAVING SUM(unit) >= 100) AS aggregated
7JOIN Products p ON aggregated.product_id = p.product_id;

Complexity note: This complexity is due to a single pass through the Orders table to aggregate units, leading to linear time complexity.

  • 1Understanding how to filter and aggregate data is crucial.
  • 2Using joins effectively can simplify data retrieval.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.