Customer Placing the Largest Number of Orders
LeetCode 586 | Difficulty: Easyβ
EasyProblem Descriptionβ
Table: Orders
+-----------------+----------+
| Column Name | Type |
+-----------------+----------+
| order_number | int |
| customer_number | int |
+-----------------+----------+
order_number is the primary key (column with unique values) for this table.
This table contains information about the order ID and the customer ID.
Write a solution to find the customer_number for the customer who has placed the largest number of orders.
The test cases are generated so that exactly one customer will have placed more orders than any other customer.
The result format is in the following example.
Example 1:
Input:
Orders table:
+--------------+-----------------+
| order_number | customer_number |
+--------------+-----------------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 3 |
+--------------+-----------------+
Output:
+-----------------+
| customer_number |
+-----------------+
| 3 |
+-----------------+
Explanation:
The customer with number 3 has two orders, which is greater than either customer 1 or 2 because each of them only has one order.
So the result is customer_number 3.
Follow up: What if more than one customer has the largest number of orders, can you find all the customer_number in this case?
Topics: Database
Approachβ
Direct Approachβ
This problem can typically be solved with straightforward iteration or simple data structure usage. Focus on correctness first, then optimize.
When to use
Basic problems that test fundamental programming skills.
Solutionsβ
Solution 1: MySQL (Best: 1191 ms)β
| Metric | Value |
|---|---|
| Runtime | 1191 ms |
| Memory | N/A |
| Date | 2018-05-08 |
Solution
# Write your MySQL query statement below
SELECT customer_number
FROM orders O
GROUP BY customer_number
ORDER BY count(*) DESC
limit 1
π 1 more MySQL submission(s)
Submission (2018-05-08) β 1235 ms, N/Aβ
# Write your MySQL query statement below
select customer_number from (select customer_number, count(*) as cnt from orders O group by customer_number order by count(*) desc) AS A limit 1
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.
- LeetCode provides 1 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: MySQL uses a different expression to get the first records other than MSSQL's TOP expression.