Talentd
FleetCode
Make and follow sheets.Sign in

Calculate Orders Within Each Interval solution and explanation

MediumDatabase4 min read67.2% acceptanceUpdated 24 Mar 2026Premium elsewhere, free here
Leetcode MEDIUM 2893 - Orders Within Each Interval - Using CEIL in SQL | Everyday Data ScienceEveryday Data Science · 4:33 · 502 viewsWatch on YouTube

The problem

Table: Orders

+-------------+------+ 
| Column Name | Type | 
+-------------+------+ 
| minute      | int  | 
| order_count | int  |
+-------------+------+
minute is the primary key for this table.
Each row of this table contains the minute and number of orders received during that specific minute. The total number of rows will be a multiple of 6.

Write a query to calculate total orders within each interval. Each interval is defined as a combination of 6 minutes.

  • Minutes 1 to 6 fall within interval 1, while minutes 7 to 12 belong to interval 2, and so forth.

Return the result table ordered by interval_no in ascending order.

The result format is in the following example.

Example 1:

Input: 
Orders table:
+--------+-------------+
| minute | order_count | 
+--------+-------------+
| 1      | 0           |
| 2      | 2           | 
| 3      | 4           | 
| 4      | 6           | 
| 5      | 1           | 
| 6      | 4           | 
| 7      | 1           | 
| 8      | 2           | 
| 9      | 4           | 
| 10     | 1           | 
| 11     | 4           | 
| 12     | 6           | 
+--------+-------------+
Output: 
+-------------+--------------+
| interval_no | total_orders | 
+-------------+--------------+
| 1           | 17           | 
| 2           | 18           |    
+-------------+--------------+
Explanation: 
- Interval number 1 comprises minutes from 1 to 6. The total orders in these six minutes are (0 + 2 + 4 + 6 + 1 + 4) = 17.
- Interval number 2 comprises minutes from 7 to 12. The total orders in these six minutes are (1 + 2 + 4 + 1 + 4 + 6) = 18.
Returning table orderd by interval_no in ascending order.

Approach overview

Problem Overview: You are given a table of time intervals and another table containing order timestamps. For each interval, compute how many orders occurred between its start and end time. The result should return the interval along with the total number of orders that fall inside that range.

Approach 1: Correlated Subquery Count (O(n * m) time, O(1) space)

The most direct approach runs a correlated subquery for every interval. For each row in the intervals table, execute a SELECT COUNT(*) on the orders table where the order timestamp falls between start_time and end_time. This works because each interval independently checks all orders. The downside is performance: if there are n intervals and m orders, the database may scan the orders table repeatedly. This method is easy to write but does not scale well for large datasets.

Approach 2: Range Join with Aggregation (O(n + m) to O(n log m) depending on indexing, O(1) extra space)

The efficient solution performs a LEFT JOIN between the intervals table and the orders table using a range condition such as orders.order_time BETWEEN intervals.start_time AND intervals.end_time. After joining, group the results by the interval identifier and use COUNT(order_id) to compute how many orders fall in that range. Because the database can leverage indexes on the order timestamp, it avoids repeated scans and evaluates the condition efficiently. This pattern is a classic range join problem in SQL and frequently appears in analytics-style queries.

Using a LEFT JOIN ensures intervals with zero orders still appear in the result. The GROUP BY aggregation then collapses matching rows into a single count per interval. Most relational databases optimize this pattern well when indexes exist on the timestamp column.

Recommended for interviews: The range join with aggregation is the expected approach. It demonstrates correct use of database querying patterns such as conditional joins, grouping, and counting. Mentioning the correlated subquery approach shows baseline understanding, but using a join with GROUP BY shows stronger SQL skills and familiarity with scalable JOIN operations.

Solution

# Write your MySQL query statement below
WITH
    T AS (
        SELECT
            minute,
            SUM(order_count) OVER (
                ORDER BY minute
                ROWS 5 PRECEDING
            ) AS total_orders
        FROM Orders
    )
SELECT minute / 6 AS interval_no, total_orders
FROM T
WHERE minute % 6 = 0;
Try this approach in the editor

Complexity analysis

ApproachTimeSpaceWhen to Use
Correlated Subquery CountO(n * m)O(1)Small datasets or quick prototypes where query simplicity matters more than performance
Range Join with GROUP BYO(n + m) to O(n log m)O(1)Production queries or interview solutions where indexed joins efficiently count orders per interval

Frequently asked questions

Is Calculate Orders Within Each Interval easy or hard?

Calculate Orders Within Each Interval is rated Medium difficulty. The challenge comes from recognizing that a range join combined with GROUP BY is more efficient than running separate counts for every interval.

Calculate Orders Within Each Interval Python/Java solution

This problem is primarily solved with SQL. In application languages like Python or Java, you would typically query the database using the SQL range join solution and process the result set rather than implementing the interval counting logic manually.

How to solve Calculate Orders Within Each Interval in O(n)?

Use a LEFT JOIN between intervals and orders with a BETWEEN condition on the order timestamp, then aggregate with COUNT and GROUP BY the interval columns. With an index on the order timestamp, the database can efficiently locate matching rows, approaching linear performance for practical workloads.

What is the best approach for Calculate Orders Within Each Interval?

The best approach uses a range JOIN between the intervals table and the orders table. Join rows where order_time falls between start_time and end_time, then GROUP BY the interval and count matching orders. This avoids repeated scans and scales well when the order timestamp column is indexed.

Is Calculate Orders Within Each Interval asked at Google/Amazon/Meta?

Range aggregation and interval counting queries appear frequently in SQL interviews at companies like Amazon, Google, and Meta. Variations often involve event logs, session windows, or time‑based analytics where candidates must count records within defined ranges.

What data structure is used in Calculate Orders Within Each Interval?

The problem relies on relational database tables and SQL operations rather than traditional data structures. The key techniques are range joins, conditional filtering with BETWEEN, and aggregation using GROUP BY and COUNT.

What is the time complexity of Calculate Orders Within Each Interval?

The optimized SQL solution using a range join and GROUP BY typically runs in O(n + m) to O(n log m) depending on indexing and query planning. n is the number of intervals and m is the number of orders. Without indexes, the database may fall back to slower scans.

Comments

Now write it yourselfClose this page and solve Calculate Orders Within Each Interval in the editor, without looking.
Practise Calculate Orders Within Each Interval