#3564

Seasonal Sales Analysis

Medium
DatabaseHash MapArray
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)

By categorizing sales into seasons and aggregating quantities in a single pass, we achieve efficiency.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a mapping of seasons to their respective months.
  2. 2Step 2: Iterate through sales, summing quantities for each category in the corresponding season.
  3. 3Step 3: For each season, determine the category with the maximum quantity sold.
solution.py9 lines
1# Full working Python code
2SELECT season, category
3FROM (SELECT CASE WHEN MONTH(sale_date) IN (12, 1, 2) THEN 'Winter' WHEN MONTH(sale_date) IN (3, 4, 5) THEN 'Spring' WHEN MONTH(sale_date) IN (6, 7, 8) THEN 'Summer' ELSE 'Fall' END AS season,
4            p.category,
5            SUM(s.quantity) AS total_quantity
6      FROM sales s JOIN products p ON s.product_id = p.product_id
7      GROUP BY season, p.category) AS seasonal_sales
8GROUP BY season, category
9HAVING total_quantity = (SELECT MAX(total_quantity) FROM seasonal_sales WHERE season = seasonal_sales.season);

Complexity note: Single pass through sales data allows for linear complexity.

  • 1Understanding seasonality can help in inventory management.
  • 2Aggregating data efficiently is crucial for performance.

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