#1321

Restaurant Growth

Medium
DatabaseSliding WindowAggregation
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)

The optimal solution uses a sliding window technique to maintain a rolling sum of the last 7 days' amounts, allowing us to compute the average in constant time for each day after the initial setup.

⚙️

Algorithm

6 steps
  1. 1Step 1: Create a temporary table to store the daily total amounts.
  2. 2Step 2: Initialize a variable to keep track of the sum of amounts for the last 7 days.
  3. 3Step 3: For each day, add the current day's amount to the sum and subtract the amount from the day that is 7 days before.
  4. 4Step 4: Calculate the average using the current sum and the number of days (up to 7).
  5. 5Step 5: Round the average to two decimal places.
  6. 6Step 6: Store the result and return it ordered by visited_on.
solution.py10 lines
1WITH DailyTotals AS (
2    SELECT visited_on, SUM(amount) AS total_amount
3    FROM Customer
4    GROUP BY visited_on
5)
6SELECT visited_on, ROUND(SUM(total_amount) / LEAST(7, COUNT(*)), 2) AS average_amount
7FROM DailyTotals
8WHERE visited_on >= DATE_SUB(visited_on, INTERVAL 6 DAY)
9GROUP BY visited_on
10ORDER BY visited_on;

Complexity note: This complexity is more efficient because we only traverse the data once to compute the daily totals, and then we use a sliding window to compute the averages.

  • 1Using a sliding window can significantly reduce the time complexity of problems involving moving averages.
  • 2Understanding how to aggregate data efficiently in SQL is crucial for performance.

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