#1587
Bank Account Summary II
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)
This approach uses a single pass to calculate the balances while iterating through the transactions, which is more efficient than the brute-force method. We use a hash map to store balances, allowing for quick updates and lookups.
⚙️
Algorithm
4 steps- 1Step 1: Create a hash map to store the balance for each account.
- 2Step 2: Iterate through the transactions and update the balances in the hash map.
- 3Step 3: After processing all transactions, filter the accounts with balances greater than 10000.
- 4Step 4: Join the results with the Users table to get the names.
solution.py14 lines
1# Full working Python code
2import pandas as pd
3
4# Sample data
5users = pd.DataFrame({'account': [900001, 900002, 900003], 'name': ['Alice', 'Bob', 'Charlie']})
6transactions = pd.DataFrame({'trans_id': [1, 2, 3, 4], 'account': [900001, 900001, 900002, 900003], 'amount': [15000, -2000, 5000, 20000]})
7
8# Optimal approach
9balances = transactions.groupby('account')['amount'].sum().reset_index()
10balances = balances[balances['amount'] > 10000]
11result = users[users['account'].isin(balances['account'])].merge(balances, on='account')
12result = result[['name', 'amount']].rename(columns={'amount': 'balance'})
13
14print(result)ℹ
Complexity note: The time complexity is O(n) because we only pass through the transactions once to calculate balances, and the space complexity is O(n) due to the storage of balances in a hash map.
- 1Using a hash map allows for efficient balance calculations.
- 2Filtering results after processing all transactions minimizes unnecessary computations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.