#3220
Odd and Even Transactions
MediumDatabaseHash 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 functions in SQL to compute the sums directly in one pass over the data. This is efficient because it reduces the number of iterations needed to compute the sums for each date.
⚙️
Algorithm
4 steps- 1Step 1: Use a single SQL query that groups transactions by transaction_date.
- 2Step 2: Use conditional aggregation to calculate the odd and even sums in the same query.
- 3Step 3: Ensure to handle cases where there are no odd or even transactions by using SUM with CASE statements.
- 4Step 4: Order the results by transaction_date.
solution.py7 lines
1# Full working Python code
2SELECT transaction_date,
3 COALESCE(SUM(CASE WHEN MOD(transaction_id, 2) = 1 THEN amount END), 0) AS odd_sum,
4 COALESCE(SUM(CASE WHEN MOD(transaction_id, 2) = 0 THEN amount END), 0) AS even_sum
5FROM transactions
6GROUP BY transaction_date
7ORDER BY transaction_date;ℹ
Complexity note: This complexity is linear because we only pass through the transactions table once to compute the sums.
- 1Using conditional aggregation can simplify the query and improve performance.
- 2Handling cases with no transactions is crucial to avoid null results.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.