#1179
Reformat Department Table
EasyDatabaseHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses aggregation with conditional statements to transform the data in a single pass. This reduces the need for multiple iterations over the data, making it much more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Use a SQL query to group the data by department id.
- 2Step 2: Use conditional aggregation to create revenue columns for each month.
- 3Step 3: Return the result in the desired format.
solution.py15 lines
1SELECT id,
2 MAX(CASE WHEN month = 'Jan' THEN revenue END) AS Jan_Revenue,
3 MAX(CASE WHEN month = 'Feb' THEN revenue END) AS Feb_Revenue,
4 MAX(CASE WHEN month = 'Mar' THEN revenue END) AS Mar_Revenue,
5 MAX(CASE WHEN month = 'Apr' THEN revenue END) AS Apr_Revenue,
6 MAX(CASE WHEN month = 'May' THEN revenue END) AS May_Revenue,
7 MAX(CASE WHEN month = 'Jun' THEN revenue END) AS Jun_Revenue,
8 MAX(CASE WHEN month = 'Jul' THEN revenue END) AS Jul_Revenue,
9 MAX(CASE WHEN month = 'Aug' THEN revenue END) AS Aug_Revenue,
10 MAX(CASE WHEN month = 'Sep' THEN revenue END) AS Sep_Revenue,
11 MAX(CASE WHEN month = 'Oct' THEN revenue END) AS Oct_Revenue,
12 MAX(CASE WHEN month = 'Nov' THEN revenue END) AS Nov_Revenue,
13 MAX(CASE WHEN month = 'Dec' THEN revenue END) AS Dec_Revenue
14FROM Department
15GROUP BY id;ℹ
Complexity note: The time complexity is linear because we only need to scan through the data once to aggregate it, while the space complexity is linear due to the storage of results.
- 1Using conditional aggregation can simplify complex queries.
- 2Understanding how to group data efficiently is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.