#1193

Monthly Transactions I

Medium
DatabaseHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses SQL's aggregation functions and grouping capabilities to efficiently compute the required values in a single scan of the Transactions table. This avoids the need for nested loops and reduces the overall complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use the DATE_FORMAT function to extract the month from trans_date.
  2. 2Step 2: Group the results by the formatted month and country.
  3. 3Step 3: Use COUNT and SUM functions to calculate the total transactions, approved transactions, and their respective amounts.
solution.py8 lines
1SELECT DATE_FORMAT(trans_date, '%Y-%m') AS month,
2       country,
3       COUNT(*) AS trans_count,
4       SUM(state = 'approved') AS approved_count,
5       SUM(amount) AS trans_total_amount,
6       SUM(CASE WHEN state = 'approved' THEN amount ELSE 0 END) AS approved_total_amount
7FROM Transactions
8GROUP BY month, country;

Complexity note: The complexity is O(n) because we only scan the Transactions table once to compute the aggregates, which is efficient.

  • 1Understanding how to use SQL aggregation functions can significantly reduce the complexity of queries.
  • 2Grouping data effectively allows for efficient computation of totals and counts.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.