Problem
Table: OrdersDetails
+-------------+------+
| Column Name | Type |
+-------------+------+
| order_id | int |
| product_id | int |
| quantity | int |
+-------------+------+
(order_id, product_id) is the primary key (combination of columns with unique values) for this table.
A single order is represented as multiple rows, one row for each product in the order.
Each row of this table contains the quantity ordered of the product product_id in the order order_id.
You are running an e-commerce site that is looking for imbalanced orders. An imbalanced order is one whose maximum quantity is strictly greater than the average quantity of every order (including itself).
The average quantity of an order is calculated as (total quantity of all products in the order) / (number of different products in the order)
. The
maximum quantity of an order is the highest quantity
of any single product in the order.
Write a solution to find the order_id
of all imbalanced orders.
Return the result table in any order.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 – Aggregation and Comparison
Intuition
We need to find orders whose maximum quantity is strictly greater than the average quantity of every order. This means, for each order, its max quantity must be greater than the max average among all orders. We can precompute the average for each order, then compare each order’s max quantity to the maximum of all averages.
Approach
- Compute the average quantity for each order (sum/number of products).
- Compute the maximum quantity for each order.
- Find the maximum average among all orders.
- Select orders whose maximum quantity is strictly greater than the maximum average.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(N)
, where N is the number of rows in OrdersDetails. Each aggregation and comparison is linear in the number of rows. - 🧺 Space complexity:
O(M)
, where M is the number of unique orders, for storing averages and maximums.