{x}
blog image

Account Balance

Solution Explanation

This problem requires calculating the running balance for each account in the Transactions table. The solution uses a window function in MySQL to efficiently achieve this.

Approach

The core idea is to use the SUM() OVER() window function. This function calculates a running sum within a defined window (partition and order).

  1. PARTITION BY account_id: This divides the data into groups based on account_id. The running sum is calculated separately for each account.

  2. ORDER BY day: This specifies the order within each partition. The running sum is calculated in ascending order of the transaction date (day).

  3. SUM(IF(type = 'Deposit', amount, -amount)): This is the expression for the running sum. It checks the transaction type (type). If it's a Deposit, the amount is added; otherwise (for Withdraw), the amount is subtracted. This ensures that withdrawals reduce the balance.

  4. ORDER BY 1, 2: This final ORDER BY clause sorts the result set first by account_id (ascending) and then by day (ascending), as required by the problem statement.

MySQL Code Explained

SELECT
    account_id,
    day,
    SUM(IF(type = 'Deposit', amount, -amount)) OVER (
        PARTITION BY account_id
        ORDER BY day
    ) AS balance
FROM Transactions
ORDER BY 1, 2;
  • SELECT account_id, day: Selects the account ID and transaction day.
  • SUM(...) OVER (...) AS balance: This is the window function. The SUM(...) calculates the running sum, and the OVER (...) clause defines the window.
  • PARTITION BY account_id: The running sum is calculated for each account separately.
  • ORDER BY day: The running sum is computed in chronological order within each account.
  • FROM Transactions: Specifies the table to query.
  • ORDER BY 1, 2: Sorts the results by account_id (column 1) and then day (column 2).

Time Complexity Analysis

The time complexity of this solution is dominated by the window function. While the exact complexity depends on the database engine's optimization, it's generally considered to be O(N log N) in the worst case, where N is the number of rows in the Transactions table. This is because the window function needs to sort the data within each partition to calculate the running sum. In practice, however, highly optimized database engines often achieve better performance than a naive O(N log N) sorting algorithm.

Space Complexity Analysis

The space complexity is O(N) in the worst case because, in principle, the query needs to store the intermediate results of the window function for each row. However, the actual memory usage will again depend on database optimizations. The output size will be at most the size of the input, so the space complexity is also linear to the input size.