#1158
Market Analysis I
MediumDatabaseHash MapAggregationJOINs
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + m)Space O(n)
The optimal solution uses a single pass through the orders to create a count of orders per user for 2019, then joins this with the Users table. This significantly reduces the number of operations needed.
⚙️
Algorithm
3 steps- 1Step 1: Create a temporary table that counts orders per buyer_id for the year 2019.
- 2Step 2: Join this temporary table with the Users table to get the user details.
- 3Step 3: Select user_id, join_date, and the order count from the joined result.
solution.py7 lines
1SELECT u.user_id, u.join_date, IFNULL(order_count, 0) AS order_count
2FROM Users u
3LEFT JOIN (SELECT buyer_id, COUNT(order_id) AS order_count
4 FROM Orders
5 WHERE YEAR(order_date) = 2019
6 GROUP BY buyer_id) o
7ON u.user_id = o.buyer_id;ℹ
Complexity note: The complexity is linear because we make one pass through the Orders table (m) to count orders and one pass through the Users table (n) to join results.
- 1Using aggregation functions like COUNT() can simplify counting operations.
- 2Joining tables effectively can reduce the need for nested loops.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.