Filter Bank Transfers and Summarize by Source Account
Arrays & HashingAuto-graded · 15 test casesLast updated
Tests ability to validate records against a lookup table, apply multi-condition filtering, and aggregate results into ranked frequency counts.
Background
A payment processor receives a batch of transfer requests alongside a snapshot of known accounts. Before any transfer can be processed, it must pass a series of checks. Your job is to run those checks and produce a summary report.
Input
You receive two lists of dictionaries.
accounts — each entry describes one account:
| Key | Type | Description |
|---|---|---|
"accountNumber" | str | Unique account identifier |
"balance" | str | Current balance, represented as a numeric string |
transactions — each entry describes one transfer attempt:
| Key | Type | Description |
|---|---|---|
"fromAccountNumber" | str | Source account |
"toAccountNumber" | str | Destination account |
"transferAmount" | str | Amount to transfer, represented as a numeric string |
Task
A transaction is valid if all three of the following hold:
fromAccountNumberexists inaccounts.toAccountNumberexists inaccounts.transferAmount(as a float) is less than or equal to thebalanceof the source account (also parsed as a float).
Return a dictionary with exactly these three keys:
"valid_transactions" — the list of transaction dictionaries that passed all three checks, in the same order they appeared in the input.
"distinct_source_accounts" — an integer: the number of unique fromAccountNumber values that appear across the valid transactions.
"transactions_per_account" — a dictionary mapping fromAccountNumber to its count of valid transactions, limited to the top 10 source accounts by count. When two accounts have the same count, the one that comes first alphabetically appears first. The dictionary must preserve this order.
Constraints
0 <= len(accounts) <= 10^40 <= len(transactions) <= 10^5- All balance and transfer amount values are non-negative numeric strings parseable by
float(). - Account numbers are non-empty strings; they may contain letters and digits.
- An account number may appear more than once in
accounts; treat its first occurrence as authoritative for the balance lookup. - The same transaction dictionary may appear more than once in
transactions; each occurrence is evaluated independently. - If fewer than 10 distinct source accounts exist in the valid set, return all of them.
- If no valid transactions exist,
"distinct_source_accounts"is0and"transactions_per_account"is{}.
Examples
Example 1
Input: banking_transaction_report([{'accountNumber': 'A1', 'balance': '100'}, {'accountNumber': 'A2', 'balance': '50'}, {'accountNumber': 'A3', 'balance': '0'}], [{'fromAccountNumber': 'A1', 'toAccountNumber': 'A2', 'transferAmount': '75'}, {'fromAccountNumber': 'A2', 'toAccountNumber': 'A3', 'transferAmount': '50'}, {'fromAccountNumber': 'A1', 'toAccountNumber': 'A3', 'transferAmount': '101'}, {'fromAccountNumber': 'A4', 'toAccountNumber': 'A1', 'transferAmount': '10'}])
Output: {'valid_transactions': [{'fromAccountNumber': 'A1', 'toAccountNumber': 'A2', 'transferAmount': '75'}, {'fromAccountNumber': 'A2', 'toAccountNumber': 'A3', 'transferAmount': '50'}], 'distinct_source_accounts': 2, 'transactions_per_account': {'A1': 1, 'A2': 1}}
Example 2
Input: banking_transaction_report([{'accountNumber': '1', 'balance': '10'}, {'accountNumber': '2', 'balance': '10'}], [{'fromAccountNumber': '1', 'toAccountNumber': '2', 'transferAmount': '10'}])
Output: {'valid_transactions': [{'fromAccountNumber': '1', 'toAccountNumber': '2', 'transferAmount': '10'}], 'distinct_source_accounts': 1, 'transactions_per_account': {'1': 1}}
Hints
Hint 1
Build a balance lookup dictionary from `accounts` first — a single pass through that list is enough, and it makes all three validation checks O(1) per transaction.
Hint 2
The three validity conditions must all be true simultaneously, so check existence for both endpoints before you attempt the float comparison to avoid a KeyError.
Hint 3
For the top-10 ranking, sort by (-count, account_number) so ties break alphabetically, then slice to 10 before building the output dictionary.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution has three sequential stages that each do one clear job.
Stage 1 — build the balance map.
Iterate through accounts once and store accountNumber → float(balance) in a dictionary. Checking membership and retrieving a balance is then O(1) for every subsequent lookup. Processing only the first occurrence of a duplicate account number keeps the behavior deterministic.
Stage 2 — filter valid transactions.
For each transaction, apply the three rules in an order that short-circuits cheaply: existence of the source account first (a dict lookup), existence of the destination account second (another dict lookup), and the balance comparison last (which requires a float() conversion). Preserving the original list order is automatic because a list comprehension iterates in order.
Stage 3 — aggregate and rank.
Counter tallies valid transactions per source account in a single pass. To produce the top-10 ranking, sort the keys by (-count, account_number) so higher counts sort first and ties resolve alphabetically. Slicing to 10 before building the output dict keeps memory and iteration bounded. Dict insertion order in Python 3.7+ preserves the sort order, which is what the grader relies on.
Why it is correct.
- All three validity conditions are evaluated together; a transaction that passes two but not the third is correctly excluded.
distinct_source_accountscounts keys inCounter, which are exactly the unique source accounts that appear in at least one valid transaction.- The alphabetical tie-break in the sort key makes the ranking deterministic regardless of the order accounts happen to appear in the input.
- Edge cases: an empty
accountslist leavesbalancesempty, so every transaction fails rules 1 and 2, and the result isvalid=[], distinct=0, top={}. An emptytransactionslist produces the same empty result trivially.
Complexity.
- Time: O(A + T + S log S), where A is the number of accounts, T is the number of transactions, and S ≤ T is the number of distinct valid source accounts. The sort dominates only when S is large, and S is capped at 10 for the final slice.
- Space: O(A + V), where V is the number of valid transactions stored in the output list.
from collections import Counter
from typing import Dict, List
def banking_transaction_report(
accounts: List[Dict[str, str]],
transactions: List[Dict[str, str]],
) -> Dict[str, object]:
# Build balance lookup; first occurrence wins for duplicate account numbers.
balances: Dict[str, float] = {}
for row in accounts:
acct = row["accountNumber"]
if acct not in balances:
balances[acct] = float(row["balance"])
# Filter transactions against all three validity rules.
valid = [
row for row in transactions
if row["fromAccountNumber"] in balances
and row["toAccountNumber"] in balances
and float(row["transferAmount"]) <= balances[row["fromAccountNumber"]]
]
# Count valid transactions per source account.
counts: Counter = Counter(row["fromAccountNumber"] for row in valid)
# Top 10: primary sort by count descending, secondary by account name ascending.
top_keys = sorted(counts, key=lambda acct: (-counts[acct], acct))[:10]
return {
"valid_transactions": valid,
"distinct_source_accounts": len(counts),
"transactions_per_account": {acct: counts[acct] for acct in top_keys},
}