Domain 1EasyCORE

Bank Account Summary II

The problem requires summarizing bank account transactions for a given list of accounts. Each transaction includes an account name, type (income or expense), and amount. The goal is to calculate the net balance for each account by summing up all income and expenses.

Domain: Easy•Updated: 2026-08-31
#Algorithms#LeetCode#qwen2.5-coder:14b#**FAANG asked:** 0

1587. Bank Account Summary II

Model: qwen2.5-coder:14b
Topics:
FAANG asked: 0
Acceptance rate: 89.9%


Problem Breakdown

The problem requires summarizing bank account transactions for a given list of accounts. Each transaction includes an account name, type (income or expense), and amount. The goal is to calculate the net balance for each account by summing up all income and expenses.

Inputs:

  • A table Transactions with columns:
    • account_name: string representing the name of the bank account.
    • type: string indicating whether the transaction is an ‘income’ or ‘expense’.
    • amount: integer representing the amount of the transaction.

Outputs:

  • A table with two columns:
    • account_name: string representing the name of the bank account.
    • balance: integer representing the net balance (sum of all incomes minus sum of all expenses) for that account.

Implicit Constraints or Tricky Edge Cases:

  • The input list can be empty, resulting in an empty output.
  • There might be duplicate account names, which should be aggregated correctly.
  • Negative amounts are possible and should be handled appropriately.
  • Overflow is not a concern as the problem specifies integer amounts.

Intuition

The brute-force approach would involve iterating through each transaction, maintaining a dictionary to accumulate balances for each account. This approach has a time complexity of O(n) where n is the number of transactions, but it requires additional space proportional to the number of unique accounts (O(m)).

A better approach leverages SQL’s aggregation capabilities to directly compute the net balance for each account in a single pass through the data, reducing both time and space complexity.

Approach

  1. Grouping: Use the GROUP BY clause on account_name to aggregate transactions by account.
  2. Aggregation: For each group, use conditional aggregation with SUM(CASE WHEN type = 'income' THEN amount ELSE 0 END) to sum up incomes and SUM(CASE WHEN type = 'expense' THEN amount ELSE 0 END) to sum up expenses.
  3. Balance Calculation: Subtract the total expenses from the total incomes to get the net balance for each account.

Complexity Analysis

  • Time Complexity: O(n), where n is the number of transactions. This is because we need to process each transaction once.
  • Space Complexity: O(m), where m is the number of unique accounts, due to the storage required for grouping results.

Solution

import pandas as pd

def account_summary(transactions: pd.DataFrame) -> pd.DataFrame:
    # Group by account_name and calculate net balance using conditional aggregation
    summary = transactions.groupby('account_name').agg(
        income=('amount', lambda x: (x * (transactions['type'] == 'income')).sum()),
        expense=('amount', lambda x: (x * (transactions['type'] == 'expense')).sum())
    ).reset_index()
    
    # Calculate net balance
    summary['balance'] = summary['income'] - summary['expense']
    
    # Return the result with only account_name and balance columns
    return summary[['account_name', 'balance']]

Edge Cases Handled

  • Empty Input: If the input DataFrame is empty, the groupby operation will naturally return an empty DataFrame.
  • Duplicate Account Names: The GROUP BY clause in SQL automatically handles duplicates by aggregating them into a single entry.
  • Negative Amounts: The conditional aggregation correctly sums up negative amounts as expenses, resulting in the correct net balance calculation.