Space
Open
From Fieldwork
Scales
Archive
from typing import List, Dict, Tuple
class LedgerSystem:
def __init__(self):
# Determine strictness of processing
self.balances: Dict[str, int] = {}
# To track duplicates: Set of (timestamp, user_id, amount)
self.seen_transactions = set()
def parse_transaction(self, transaction_str: str) -> Tuple[int, str, int]:
"""
Helper to cleanly parse the input string.
Returns: (timestamp, user_id, amount)
"""
parts = transaction_str.split(',')
timestamp = int(parts[0].strip())
user_id = parts[1].strip()
amount = int(parts[2].strip())
return timestamp, user_id, amount
def process_transactions(self, transactions: List[str]) -> Dict[str, int]:
self.balances = {}
self.seen_transactions = set()
# Step 1: Parse all transactions first
parsed_data = []
for t_str in transactions:
parsed_data.append(self.parse_transaction(t_str))
# Step 2: Sort by timestamp (Required for Part 3)
# Python's sort is stable and efficient (Timsort)
parsed_data.sort(key=lambda x: x[0])
for timestamp, user, amount in parsed_data:
# Part 2: Duplicate Check
# We construct a unique signature for the transaction
txn_signature = (timestamp, user, amount)
if txn_signature in self.seen_transactions:
continue
self.seen_transactions.add(txn_signature)
# Part 3: Overdraft Check
current_balance = self.balances.get(user, 0)
if current_balance + amount < 0:
# Reject transaction (do nothing)
# In a real interview, you might want to log this rejection
continue
# Apply transaction
self.balances[user] = current_balance + amount
return self.balances
# --- Test Cases (How you should verify your code in the interview) ---
def run_tests():
solver = LedgerSystem()
# Test Part 1: Basic logic
t1 = [
"100, user_a, 100",
"105, user_b, 50",
"110, user_a, -20"
]
assert solver.process_transactions(t1) == {'user_a': 80, 'user_b': 50}, "Failed Part 1"
# Test Part 2: Duplicates
t2 = [
"100, user_a, 100",
"100, user_a, 100", # Dup
"110, user_a, 50"
]
assert solver.process_transactions(t2) == {'user_a': 150}, "Failed Part 2"
# Test Part 3: Chronological Order & Overdraft
t3 = [
"200, user_a, -50", # Should process 2nd (Balance 100 -> 50)
"100, user_a, 100", # Should process 1st (Balance 0 -> 100)
"300, user_a, -60" # Should process 3rd (Balance 50 -> -10 REJECT)
]
result_t3 = solver.process_transactions(t3)
assert result_t3 == {'user_a': 50}, f"Failed Part 3. Got {result_t3}"
print("All tests passed!")
if __name__ == "__main__":
run_tests()Practice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode