Progressive Banking System Level 1 to 4
1. Introduction to the problem
This is a CodeSignal Progressive Coding Assessment with four levels in total. It mainly tests data structures, object-oriented programming, business logic implementation and extensibility of the code, rather than traditional LeetCode algorithms.
The format is "Filesystem with Unit Tests". You implement the BankingSystemImpl class in banking_system_impl.py. Each level builds on the functionality of the previous ones.
| Level | Features | What it tests |
|---|---|---|
| Level 1 | Create Account, Deposit, Transfer | HashMap |
| Level 2 | Top Spenders | Sorting, Lambda |
| Level 3 | Pay, Cashback, Payment Status | Min Heap, State Management |
| Level 4 | Merge Accounts, Get Balance | Historical Data, Account Lifecycle |
Note that there are several versions of Banking System floating around online. In some versions Level 3 is Scheduled Payment and Cancel Payment, while this version deducts the money immediately and returns 2% cashback after 24 hours.
Levels 1 to 3 below are organized from the actual problem and screenshots. Level 4 is reconstructed from the common version and has not been checked against the real problem. The full code has not been verified by the official judge.
2. Level 1: Basic Banking System
1. create_account
create_account(self, timestamp: int, account_id: str) -> bool
Creates a bank account with an initial balance of 0. If the account already exists, return False. If it is created successfully, return True.
2. deposit
deposit(self, timestamp: int, account_id: str, amount: int) -> int | None
Deposits an amount into the given account. If the account does not exist, return None. After a successful deposit, return the latest balance.
3. transfer
transfer(self, timestamp: int, source_account_id: str,
target_account_id: str, amount: int) -> int | None
Transfers money from the source account to the target account. Return None in these cases:
- The source account does not exist.
- The target account does not exist.
- Source and target are the same account.
- The source account has insufficient balance.
After a successful transfer, return the remaining balance of the source account.
Data structure
Use a nested dictionary to store the account info:
self.accounts = {
"account1": {
"balance": 1000,
"outgoing": 200
}
}
balance is the current balance and outgoing is the cumulative amount transferred out and paid. I suggest maintaining outgoing from Level 1 on, which makes later extensions easier.
3. Level 2: Top Spenders
top_spenders(self, timestamp: int, n: int) -> list[str]
Returns the top n accounts by cumulative spending. Sorting rules:
- Outgoing total descending.
- If outgoing is equal, account ID in ascending lexicographic order.
- If there are fewer than n accounts, return all of them.
Each account is output in the format account_id(outgoing). For example:
accounts = {
"account1": {"balance": 500, "outgoing": 200},
"account2": {"balance": 300, "outgoing": 500},
"account3": {"balance": 100, "outgoing": 500}
}
Calling top_spenders(timestamp, 2) gives:
["account2(500)", "account3(500)"]
The core sorting code:
rank = sorted(
self.accounts,
key=lambda x: (-self.accounts[x]['outgoing'], x)
)
4. Level 3: Payments with Cashback
Level 3 adds two operations: pay() and get_payment_status().
1. pay
pay(self, timestamp: int, account_id: str,
amount: int) -> str | None
Immediately deducts amount from the given account, and returns 2% of the payment amount (rounded down) after 24 hours. After a successful payment, return a globally unique payment ID:
"payment1"
"payment2"
"payment3"
Specific requirements:
- If the account does not exist, return
None. - If the account has insufficient balance, return
None. - Only a successful payment increments the payment counter.
- All accounts share the same payment counter.
- The amount of a successful payment counts toward outgoing.
- Cashback does not reduce outgoing.
- The cashback amount is rounded down.
Timestamps are in milliseconds, so 24 hours is:
24 * 60 * 60 * 1000 = 86400000
The actual cashback time:
due_time = timestamp + 86400000
The cashback amount:
cashback = amount * 2 // 100
If the cashback due time is the same as the time of another transaction, the cashback must be processed first, then the other transaction.
2. get_payment_status
get_payment_status(self, timestamp: int,
account_id: str, payment: str) -> str | None
Queries the status of a given payment. Return None in these cases:
- The account does not exist.
- The payment ID does not exist.
- The payment belongs to another account.
There are only two valid statuses:
"IN_PROGRESS"
"CASHBACK_RECEIVED"
Data structure design
Use a dictionary to store payment info:
self.payments = {
"payment1": {
"account": "account1",
"cashback": 20,
"status": "IN_PROGRESS"
}
}
Use a min heap to manage the cashbacks that need to be executed in the future:
self.payment_heap = []
The heap stores:
(due_time, payment_count, payment_id)
Before every banking operation, first run:
self.cashback(timestamp)
to process all cashbacks that are already due. Use while rather than if, because several cashbacks can come due at the same time point.
5. Level 4: Merge Accounts & Historical Balance
This part is reconstructed from the common CodeSignal Banking System Level 4 version. The actual exam requirements may differ.
1. merge_accounts
merge_accounts(self, timestamp: int,
account_id_1: str, account_id_2: str) -> bool
Merges account_id_2 into account_id_1. Requirements:
- If the two accounts are the same, return
False. - If either account does not exist, return
False. - Account 1 inherits the balance of Account 2.
- Account 1 inherits the cumulative outgoing of Account 2.
- Future cashbacks of Account 2 go to Account 1.
- Account 1 can query the payment status of Account 2's original payments.
- Account 2 is removed from the active accounts.
Return True on a successful merge.
2. get_balance
get_balance(self, timestamp: int,
account_id: str, time_at: int) -> int | None
Queries the balance of the given account at the historical time point time_at. If there was no transaction at that time point, return the balance after the most recent balance change. If the account had not been created yet at the given time, or has already been closed, return None.
You need to maintain extra historical balances:
self.history = {
"account1": [
(1, 0),
(3, 1000),
(5, 800),
(10, 1500)
],
"account2": [
(2, 0),
(4, 700),
(10, None)
]
}
Use (timestamp, balance) to store each balance change, and None to mean the account is closed.
One thing to watch: the history record for a cashback must use the actual due time due_time, not the current timestamp at the moment the cashback is processed.
6. Full Python solution for Levels 1 to 4
from banking_system import BankingSystem
import heapq
class BankingSystemImpl(BankingSystem):
def __init__(self):
self.accounts = {}
self.payments = {}
self.payment_heap = []
self.payment_count = 0
self.history = {}
# Record historical balance
def record_balance(self, account_id, timestamp, balance):
if account_id not in self.history:
self.history[account_id] = []
self.history[account_id].append(
(timestamp, balance)
)
# Process all due cashback
def cashback(self, timestamp):
while (self.payment_heap
and self.payment_heap[0][0] <= timestamp):
due_time, count, payment_id = heapq.heappop(
self.payment_heap
)
payment = self.payments[payment_id]
account_id = payment['account']
self.accounts[account_id]['balance'] += (
payment['cashback']
)
payment['status'] = 'CASHBACK_RECEIVED'
self.record_balance(
account_id,
due_time,
self.accounts[account_id]['balance']
)
# ====================
# Level 1
# ====================
def create_account(self, timestamp, account_id):
self.cashback(timestamp)
if account_id in self.accounts:
return False
self.accounts[account_id] = {
'balance': 0,
'outgoing': 0
}
self.record_balance(account_id, timestamp, 0)
return True
def deposit(self, timestamp, account_id, amount):
self.cashback(timestamp)
if account_id not in self.accounts:
return None
self.accounts[account_id]['balance'] += amount
self.record_balance(
account_id,
timestamp,
self.accounts[account_id]['balance']
)
return self.accounts[account_id]['balance']
def transfer(self, timestamp, source_account_id,
target_account_id, amount):
self.cashback(timestamp)
if (source_account_id not in self.accounts
or target_account_id not in self.accounts
or source_account_id == target_account_id
or self.accounts[source_account_id]['balance']
< amount):
return None
self.accounts[source_account_id]['balance'] -= amount
self.accounts[target_account_id]['balance'] += amount
self.accounts[source_account_id]['outgoing'] += amount
self.record_balance(
source_account_id,
timestamp,
self.accounts[source_account_id]['balance']
)
self.record_balance(
target_account_id,
timestamp,
self.accounts[target_account_id]['balance']
)
return self.accounts[source_account_id]['balance']
# ====================
# Level 2
# ====================
def top_spenders(self, timestamp, n):
self.cashback(timestamp)
rank = sorted(
self.accounts,
key=lambda x: (
-self.accounts[x]['outgoing'], x
)
)
res = []
for account in rank[:n]:
outgoing = self.accounts[account]['outgoing']
res.append(f"{account}({outgoing})")
return res
# ====================
# Level 3
# ====================
def pay(self, timestamp, account_id, amount):
self.cashback(timestamp)
if (account_id not in self.accounts
or self.accounts[account_id]['balance'] < amount):
return None
self.accounts[account_id]['balance'] -= amount
self.accounts[account_id]['outgoing'] += amount
self.record_balance(
account_id,
timestamp,
self.accounts[account_id]['balance']
)
cashback = amount * 2 // 100
due_time = timestamp + 86400000
self.payment_count += 1
payment_id = f"payment{self.payment_count}"
self.payments[payment_id] = {
'account': account_id,
'cashback': cashback,
'status': 'IN_PROGRESS'
}
heapq.heappush(
self.payment_heap,
(due_time, self.payment_count, payment_id)
)
return payment_id
def get_payment_status(self, timestamp,
account_id, payment):
self.cashback(timestamp)
if (account_id not in self.accounts
or payment not in self.payments
or self.payments[payment]['account']
!= account_id):
return None
return self.payments[payment]['status']
# ====================
# Level 4
# ====================
def merge_accounts(self, timestamp,
account_id_1, account_id_2):
self.cashback(timestamp)
if (account_id_1 not in self.accounts
or account_id_2 not in self.accounts
or account_id_1 == account_id_2):
return False
# Merge balance
self.accounts[account_id_1]['balance'] += (
self.accounts[account_id_2]['balance']
)
# Merge outgoing
self.accounts[account_id_1]['outgoing'] += (
self.accounts[account_id_2]['outgoing']
)
# Transfer payment ownership
for payment in self.payments.values():
if payment['account'] == account_id_2:
payment['account'] = account_id_1
# Record survivor's balance
self.record_balance(
account_id_1,
timestamp,
self.accounts[account_id_1]['balance']
)
# Mark absorbed account as closed
self.record_balance(
account_id_2,
timestamp,
None
)
del self.accounts[account_id_2]
return True
def get_balance(self, timestamp, account_id, time_at):
self.cashback(timestamp)
if account_id not in self.history:
return None
for hist_time, balance in reversed(
self.history[account_id]
):
if hist_time <= time_at:
return balance
return None
7. Data structure summary
| Variable | Data Structure | Purpose |
|---|---|---|
| accounts | Nested Dictionary | Current account info |
| payments | Nested Dictionary | Payment info and status |
| payment_heap | Min Heap | Manages when cashbacks execute |
| payment_count | Integer | Generates unique payment IDs |
| history | Dictionary of Lists | Stores historical balances |
8. Time complexity
Assume A is the number of active accounts, P is the number of payment records, and H is the number of history records of an account.
| Operation | Time Complexity |
|---|---|
| create_account | O(1) |
| deposit | O(1) |
| transfer | O(1) |
| top_spenders | O(A log A) |
| pay | O(log P) |
| get_payment_status | O(1) |
| merge_accounts | O(P) |
| get_balance | O(H) |
| Process each cashback | O(log P) |
These are the complexities of the operations themselves, not including the extra cost of processing due cashbacks before each call. Dictionary operations are counted at average time complexity.
GET_BALANCE can be further optimized to O(log H) with binary search. MERGE_ACCOUNTS can also avoid iterating over all payments by keeping a set of payment IDs for each account.
Discussion
Loading comments…