Skip to main content

Calculate Orders Within Each Interval - Solution & Explanation

MediumPremiumFree on FleetCodeDatabase4 min read
Practice this problem

Problem Statement

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

Code

MySQL

Try this approach in the editor →

Detailed 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

Video Solution

Leetcode MEDIUM 2893 - Orders Within Each Interval - Using CEIL in SQL | Everyday Data Science • Everyday Data Science • 502 views views

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.

Ready to solve this problem?

Practice Calculate Orders Within Each Interval with our built-in code editor and test cases.

Practice on FleetCode