In-Memory Expense Reimbursement Service
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement an in-memory service that processes batches of employee reimbursement commands while enforcing server-side validation rules.
Model each stored record with an Expense structure containing five fields:
id(int): a unique integer assigned sequentially starting at1(1, 2, 3, ...). Rejected creation requests do not consume an ID, deleted IDs are never reused, and any caller-providedidin an input payload must be ignored.amount(floatorint): a strictly positive, finite numeric charge (boolvalues are invalid even thoughboolsubclassesintin Python).category(str): a label for the spend type, defaulting to""when omitted.is_reimbursed(bool): whether payout has occurred; always starts asFalseupon creation regardless of any caller-provided value.description(str): a short memo for the charge, defaulting to""when omitted.
Organize the domain logic inside an ExpenseManager class and expose a batch driver manage_expenses(operations: List[str], arguments: List[List]) -> List[Dict] that runs operations[i] with arguments[i] against a fresh manager instance and collects one result per command:
"add_expense"(arguments[i] = [expense_data]): Checkexpense_data.get("amount"). If it is missing, a boolean, non-numeric, non-finite (NaNor infinity), or<= 0, return{"error": "amount must be greater than zero"}without advancing the ID counter. Otherwise store the new record and return its dictionary snapshot."delete_expense"(arguments[i] = [expense_id]): Remove the record withid == expense_idand return its dictionary snapshot. If no active record has that ID, return{"error": "expense not found"}."list_expenses"(arguments[i] = []): Return a list of dictionary snapshots for all active records in the order they were created (or[]if none exist)."toggle_reimbursement"(arguments[i] = [expense_id]): First confirm thatexpense_idexists; if not, return{"error": "expense not found"}. Next enforce the high-value cap: if the record hasamount > 1000, leaveis_reimbursedunchanged and return{"error": "approval required"}(amounts<= 1000, including1000, may be toggled freely). Otherwise flipis_reimbursedbetweenFalseandTrueand return the updated dictionary snapshot.
Every returned dictionary (and every element inside a "list_expenses" result) must be an independent snapshot captured when that command executed so later updates never alter earlier items in the output list.
Examples
Example 1
Input:
operations = ["add_expense", "add_expense", "toggle_reimbursement", "delete_expense", "list_expenses"]
arguments = [
[{"amount": 42.5, "category": "Lodging", "description": "Parking"}],
[{"amount": 18.0, "category": "Supplies", "description": "Notebook"}],
[1],
[2],
[]
]
Output:
[
{"id": 1, "amount": 42.5, "category": "Lodging", "is_reimbursed": False, "description": "Parking"},
{"id": 2, "amount": 18.0, "category": "Supplies", "is_reimbursed": False, "description": "Notebook"},
{"id": 1, "amount": 42.5, "category": "Lodging", "is_reimbursed": True, "description": "Parking"},
{"id": 2, "amount": 18.0, "category": "Supplies", "is_reimbursed": False, "description": "Notebook"},
[{"id": 1, "amount": 42.5, "category": "Lodging", "is_reimbursed": True, "description": "Parking"}]
]
Explanation: Two valid charges receive IDs 1 and 2 with is_reimbursed = False. Toggling ID 1 (42.5 <= 1000) flips its flag to True. Deleting ID 2 removes and returns that record, leaving only ID 1 in the final listing.
Example 2
Input:
operations = [
"add_expense",
"add_expense",
"add_expense",
"toggle_reimbursement",
"toggle_reimbursement",
"toggle_reimbursement",
"list_expenses"
]
arguments = [
[{"amount": 0, "category": "Software", "description": "Trial"}],
[{"amount": 1400.0, "category": "Hardware", "description": "Workstation"}],
[{"amount": 1000.0, "category": "Training", "description": "Workshop"}],
[1],
[2],
[7],
[]
]
Output:
[
{"error": "amount must be greater than zero"},
{"id": 1, "amount": 1400.0, "category": "Hardware", "is_reimbursed": False, "description": "Workstation"},
{"id": 2, "amount": 1000.0, "category": "Training", "is_reimbursed": False, "description": "Workshop"},
{"error": "approval required"},
{"id": 2, "amount": 1000.0, "category": "Training", "is_reimbursed": True, "description": "Workshop"},
{"error": "expense not found"},
[
{"id": 1, "amount": 1400.0, "category": "Hardware", "is_reimbursed": False, "description": "Workstation"},
{"id": 2, "amount": 1000.0, "category": "Training", "is_reimbursed": True, "description": "Workshop"}
]
]
Explanation: The zero-amount entry fails validation and does not consume ID 1. The 1400.0 hardware charge receives ID 1, and the 1000.0 training charge receives ID 2. Toggling ID 1 fails because 1400.0 > 1000, toggling ID 2 succeeds because 1000.0 <= 1000, and toggling unknown ID 7 reports "expense not found".
Constraints
len(operations) == len(arguments)- Every entry in
operationsis one of"add_expense","delete_expense","list_expenses", or"toggle_reimbursement". - Single-record operations (
add_expense,delete_expense,toggle_reimbursement) should run in expectedO(1)time, andlist_expensesshould run inO(n)time fornactive records. - Existence is checked before the
1000approval limit intoggle_reimbursement.
Step-by-step walkthrough
Understand the contract and layer boundaries
Our goal is an in-memory reimbursement service supporting four CRUD actions (Create, Read, Update, and Delete) guarded by server-side domain checks.
The batch entry point
manage_expenses(operations, arguments)returns one output item per command:- Valid single-item actions (
add_expense,toggle_reimbursement,delete_expense) return an expense dictionary:{"id": ..., "amount": ..., "category": ..., "is_reimbursed": ..., "description": ...}. list_expensesreturns a list of those expense dictionaries in the order they were created.- Business-rule failures return
{"error": "<message>"}with one of three exact messages:"amount must be greater than zero"when adding an expense withamount <= 0(or non-numeric input),"expense not found"when deleting or toggling a missing ID,"approval required"when toggling an expense whoseamount > 1000.
Separating the code into three clean layers keeps our business logic independent of the judge harness, just like separating a service class from HTTP controllers in a web backend:
manage_expenses(ops, args) <-- API / Judge Adapter: catches ExpenseError -> {"error": ...} | and serializes Expense objects into fresh dict snapshots v ExpenseManager <-- Domain Service: enforces IDs, lookups, and business rules | v Expense <-- Data Model (@dataclass): id, amount, category, is_reimbursed, description- Valid single-item actions (
Model `Expense` and pick an O(1) storage structure
Every single-item operation (
delete_expense,toggle_reimbursement) looks up an expense byid. If we stored expenses in a plain Pythonlist, every lookup or deletion would scan up tonitems (O(n)). Instead, we store them in a dictionaryself.expenses: Dict[int, Expense]keyed byid:- Lookup and deletion by
idtakeO(1)average time. - In Python 3.7+, dictionaries preserve insertion order, so
list(self.expenses.values())returns remaining expenses in creation order automatically!
We define
Expensewith@dataclass(a standard Python decorator that auto-generates__init__,__repr__, and equality checks from field type annotations) and define a customExpenseError(Exception)for rule violations:from dataclasses import dataclass, asdict APPROVAL_LIMIT = 1000 class ExpenseError(Exception): """Domain exception raised when an expense operation violates a business rule.""" @dataclass class Expense: id: int amount: float category: str is_reimbursed: bool description: str- Lookup and deletion by
Validate amounts safely and assign monotonic IDs
When adding an expense, three subtle bugs often trip people up in backend interviews:
- Python booleans are integers:
isinstance(True, int)isTruein Python (True == 1), so a naiveisinstance(val, (int, float)) and val > 0accidentally acceptsamount = Trueas$1! We rejectboolfirst and usemath.isfinite(value)to rejectNaNandinf. - Never trust client-supplied
idoris_reimbursed: If we unpackedExpense(**expense_data), a caller could submit{"amount": 5000, "is_reimbursed": True}and bypass the$1,000approval limit. Always setid = self.next_idandis_reimbursed = Falseon the server. - Use a monotonic counter (
self.next_id), incremented only on success: Computing IDs aslen(self.expenses) + 1reuses old IDs after a deletion, causing receipts or audit links to point at the wrong expense. And incrementingself.next_idafter validation ensures rejected requests never burn an ID.
def _is_valid_positive_amount(value: Any) -> bool: # In Python, bool is a subclass of int (isinstance(True, int) is True), # so we explicitly reject booleans before checking for int or float. if isinstance(value, bool) or not isinstance(value, (int, float)): return False # Reject NaN, +inf, -inf, zero, and negative amounts. return math.isfinite(value) and value > 0- Python booleans are integers:
Order checks carefully in `delete` and `toggle`
Both
delete_expenseandtoggle_reimbursementmust verify thatexpense_idexists first, so we extract_get_expense_or_raise(expense_id).Inside
toggle_reimbursement, check order is everything:toggle_reimbursement(expense_id) 1. Lookup expense_id --missing?--> raise ExpenseError("expense not found") 2. Check amount > 1000 --too big?--> raise ExpenseError("approval required") (state untouched!) 3. Flip expense.is_reimbursed = not expense.is_reimbursedNotice the boundary
expense.amount > APPROVAL_LIMIT(> 1000, not>= 1000): the rule says "greater than $1,000", so an expense of exactly1000can still be toggled freely.class ExpenseManager: def __init__(self) -> None: self.expenses: Dict[int, Expense] = {} self.next_id: int = 1 def _get_expense_or_raise(self, expense_id: int) -> Expense: expense = self.expenses.get(expense_id) if expense is None: raise ExpenseError("expense not found") return expense def add_expense(self, expense_data: Dict[str, Any]) -> Expense: amount = expense_data.get("amount") if not _is_valid_positive_amount(amount): raise ExpenseError("amount must be greater than zero") expense = Expense( id=self.next_id, amount=amount, category=expense_data.get("category", ""), is_reimbursed=False, description=expense_data.get("description", ""), ) self.expenses[expense.id] = expense self.next_id += 1 return expense def delete_expense(self, expense_id: int) -> Expense: expense = self._get_expense_or_raise(expense_id) del self.expenses[expense_id] return expense def list_expenses(self) -> List[Expense]: return list(self.expenses.values()) def toggle_reimbursement(self, expense_id: int) -> Expense: expense = self._get_expense_or_raise(expense_id) if expense.amount > APPROVAL_LIMIT: raise ExpenseError("approval required") expense.is_reimbursed = not expense.is_reimbursed return expenseReturn fresh dict snapshots in the driver
Why do we convert every returned
Expensewithasdict(...)inside_execute_operationinstead of storing dicts and returning them directly?Suppose
list_expenses()runs at Step 2 whenis_reimbursedisFalse, andtoggle_reimbursement(1)runs at Step 3. In a real HTTP API, the JSON response sent at Step 2 is frozen on the wire. In memory, if Step 2 appended a reference to the live dict and Step 3 mutated that same dict, Step 2's historical entry inresultswould silently flip toTrue! Callingasdict(expense)creates an independent snapshot (a fresh dictionary copy) on every call.We also catch only
ExpenseErrorinmanage_expensesso genuine bugs like an unknown operation name (ValueError) still surface immediately instead of masquerading as user errors.Trace Example 2 end to end
Step Call Outcome & State ---- ---------------------------------------- ------------------------------------------------------- 1 add_expense({amount: 0, ...}) 0 <= 0 -> {"error": "amount must be greater than zero"} expenses={}, next_id=1 (ID 1 NOT consumed!) 2 add_expense({amount: 1400.0, ...}) 1400.0 > 0 -> returns id=1 (is_reimbursed=False) expenses={1: $1400}, next_id=2 3 add_expense({amount: 1000.0, ...}) 1000.0 > 0 -> returns id=2 (is_reimbursed=False) expenses={1: $1400, 2: $1000}, next_id=3 4 toggle_reimbursement(1) id=1 found, 1400.0 > 1000 -> {"error": "approval required"} id=1 stays is_reimbursed=False 5 toggle_reimbursement(2) id=2 found, 1000.0 <= 1000 -> flips id=2 to True 6 toggle_reimbursement(7) id=7 missing -> {"error": "expense not found"} 7 list_expenses() returns [{id: 1, ..., False}, {id: 2, ..., True}]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from dataclasses import dataclass, asdict import math APPROVAL_LIMIT = 1000 class ExpenseError(Exception): """Domain exception raised when an expense operation violates a business rule.""" @dataclass class Expense: id: int amount: float category: str is_reimbursed: bool description: str def _is_valid_positive_amount(value: Any) -> bool: # In Python, bool is a subclass of int (isinstance(True, int) is True), # so we explicitly reject booleans before checking for int or float. if isinstance(value, bool) or not isinstance(value, (int, float)): return False # Reject NaN, +inf, -inf, zero, and negative amounts. return math.isfinite(value) and value > 0 class ExpenseManager: def __init__(self) -> None: # expenses: {expense_id: Expense(...)}, preserving insertion order in Python 3.7+. # Example: {1: Expense(id=1, amount=42.5, category='Lodging', is_reimbursed=False, description='Parking')} self.expenses: Dict[int, Expense] = {} # Monotonic ID counter: starts at 1 and never reuses deleted or rejected IDs. self.next_id: int = 1 def _get_expense_or_raise(self, expense_id: int) -> Expense: expense = self.expenses.get(expense_id) if expense is None: raise ExpenseError("expense not found") return expense def add_expense(self, expense_data: Dict[str, Any]) -> Expense: amount = expense_data.get("amount") if not _is_valid_positive_amount(amount): raise ExpenseError("amount must be greater than zero") # Server-side authority: assign `id` and `is_reimbursed=False` on the server # so a caller cannot spoof an ID or pre-approve a high-value expense. expense = Expense( id=self.next_id, amount=amount, category=expense_data.get("category", ""), is_reimbursed=False, description=expense_data.get("description", ""), ) # Advance `next_id` only AFTER validation succeeds so rejected calls waste no IDs. self.expenses[expense.id] = expense self.next_id += 1 return expense def delete_expense(self, expense_id: int) -> Expense: expense = self._get_expense_or_raise(expense_id) del self.expenses[expense_id] return expense def list_expenses(self) -> List[Expense]: return list(self.expenses.values()) def toggle_reimbursement(self, expense_id: int) -> Expense: # Check existence BEFORE checking the approval limit so missing IDs always # report "expense not found", and check the limit BEFORE mutating state. expense = self._get_expense_or_raise(expense_id) # Strictly `> 1000`: an expense of exactly $1,000 is still allowed without approval. if expense.amount > APPROVAL_LIMIT: raise ExpenseError("approval required") expense.is_reimbursed = not expense.is_reimbursed return expense def _execute_operation(manager: ExpenseManager, op: str, args: List[Any]) -> Any: """Dispatch one operation and serialize Expense objects into fresh dict snapshots.""" # `asdict` builds a brand-new dict copy so later toggles cannot mutate past responses. if op == "add_expense": created = manager.add_expense(args[0]) return asdict(created) if op == "delete_expense": removed = manager.delete_expense(args[0]) return asdict(removed) if op == "toggle_reimbursement": updated = manager.toggle_reimbursement(args[0]) return asdict(updated) if op == "list_expenses": snapshots: List[Dict[str, Any]] = [] for expense in manager.list_expenses(): snapshots.append(asdict(expense)) return snapshots raise ValueError(f"unknown operation: {op}") def manage_expenses(operations: List[str], arguments: List[List]) -> List[Dict]: manager = ExpenseManager() results: List[Any] = [] for op, args in zip(operations, arguments): try: results.append(_execute_operation(manager, op, args)) except ExpenseError as err: # Convert only expected domain rule failures into error response dicts; # unexpected programming bugs (e.g. ValueError, TypeError) still fail loudly. results.append({"error": str(err)}) return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of ExpenseManager as a company accounting clerk keeping an indexed binder of numbered expense vouchers on their desk, while manage_expenses is the front-desk window that translates incoming paper forms into binder updates and hands back stamped photocopies (defensive snapshots — fresh dictionary copies created at response time so later updates never overwrite historical responses). Keeping vouchers in a Python dict keyed by voucher id lets the clerk jump straight to any voucher for CRUD operations (Create, Read, Update, and Delete) without flipping through the entire binder, while Python's insertion-ordered dictionary keeps list_expenses() in clean chronological creation order.
Why do quick-and-dirty shortcuts break? Storing expenses in a plain list forces a linear scan on every toggle_reimbursement and delete_expense; generating IDs as len(expenses) + 1 instead of a monotonic counter (a counter that only moves upward and never reuses old numbers) hands out duplicate IDs after a deletion; and returning live dictionary references causes a list_expenses() snapshot taken before a toggle to mysteriously change after the toggle!
Here is a tiny 4-step trace showing how validation, ID assignment, and snapshots cooperate:
1. add_expense({amount: 42.5, ...}) -> valid! Stored at id=1 (is_reimbursed=False); next_id=2.
2. add_expense({amount: 0, ...}) -> rejected ("amount must be greater than zero"); next_id stays 2.
3. list_expenses() -> returns fresh copy [{id: 1, amount: 42.5, is_reimbursed: False, ...}].
4. toggle_reimbursement(1) -> 42.5 <= 1000 -> flips id=1 to True; Step 3's copy stays False!
Complexity
Let n be the number of expenses currently stored in ExpenseManager.
- Time:
add_expense,delete_expense,toggle_reimbursement: O(1) average. Each call validates fields in constant time, performs a singleO(1)average hash-map lookup/insert/delete onself.expenses, and copies a fixed 5-fieldExpensedataclass (a lightweight Python class generated from field annotations) into a dict viaasdict.list_expenses: O(n). Iterating over allnstored expenses and serializing each into a fresh dictionary copy does constant work per stored expense.
- Space: O(n).
self.expensesstores oneExpenseinstance per active expense, and eachlist_expenses()response allocates anO(n)list of snapshot dicts.
Edge cases
- Zero, negative, boolean, or
NaNamounts:0,-5,True(which subclassesintin Python!),float("nan"), andfloat("inf")are all rejected with"amount must be greater than zero"without advancingself.next_id. - Exact
$1,000approval boundary:amount = 1000satisfiesnot (1000 > 1000)and toggles cleanly;amount = 1000.01raises"approval required"and leavesis_reimbursedunchanged. - Unknown or already-deleted IDs: Toggling a missing ID or deleting the same ID twice raises
"expense not found". Even if a deleted expense originally hadamount = 2000, toggling its old ID reports"expense not found"(not"approval required") because existence is checked first. - ID non-reuse: Deleting ID
2never re-issues ID2; the next validadd_expensereceives ID3. - Server-controlled fields: Client-supplied
idoris_reimbursed: Trueinsideexpense_dataare ignored so callers cannot forge IDs or pre-approve high-value expenses. - Toggling twice: Flipping
not expense.is_reimburseda second time cleanly restoresFalse.
Common mistakes
- Generating IDs with
len(self.expenses) + 1: Adding two items (id=1, 2), deletingid=1(len=1), and adding a third produceslen + 1 = 2, overwriting the still-existingid=2! - Incrementing
next_idbefore validatingamount: A rejected negative expense burns an ID and leaves confusing gaps during testing. - Checking
amount > 1000before checking whether the expense exists, or mutating before checking: Always look up first, validate rules second, and mutate state last. - Writing
>= 1000instead of> 1000: The business rule restricts amounts strictly greater than$1,000. - Returning live references instead of copies: Appending internal mutable dicts directly into
resultscauses latertoggle_reimbursementcalls to mutate earlierlist_expensesoutputs. - Catching bare
Exceptionin the driver: Catching everything turns genuine code bugs (NameError,TypeError, unknown operation names) into{"error": ...}dicts instead of failing loudly; catch onlyExpenseError. - Using binary
floatfor money in production: In IEEE-754 floating point,0.1 + 0.2 == 0.30000000000000004. Real financial systems store integer cents (5000for$50.00) ordecimal.Decimal.
Alternative approaches
- Mapping
ExpenseManagerto HTTP REST endpoints: In a web service, the exact sameExpenseManagermethods sit behind thin HTTP handlers:
text
POST /expenses -> 201 Created (422 Unprocessable Content if amount <= 0)
GET /expenses -> 200 OK (with cursor pagination)
DELETE /expenses/{id} -> 200 OK with deleted item or 204 No Content (404 if missing)
POST /expenses/{id}/toggle-reimbursement -> 200 OK (404 if missing, 409 Conflict if approval required)
Follow-up questions
- What schema changes are needed to handle claims submitted in multiple currencies? Add an ISO 4217 currency code string (the three-letter international currency standard such as
"USD","EUR", or"JPY") and store amounts as exact integers in minor currency units (the smallest indivisible unit of a currency, such as2decimal places / cents for USD vs0decimal places for JPY) orDecimalrather thanfloat. Because the$1,000approval threshold is defined in the company's base currency (say USD), also recordexchange_rate_to_baseandbase_amount_centsat submission time so future currency fluctuations never retroactively alter whether a historical expense needed approval. - Which relational database indexing and query strategies would keep this service fast across millions of records? Store rows in a relational table with
idas the B-tree primary key forO(log n)point lookups, add composite indexes matching access patterns like(employee_id, created_at DESC), and speed up reviewer queues with a partial index (an index built only over rows matching aWHEREfilter, such asCREATE INDEX ... ON expenses(created_at) WHERE is_reimbursed = FALSE, keeping the index tiny once most historical expenses are paid). Replace unboundedlist_expenses()with keyset pagination (WHERE id < :cursor ORDER BY id DESC LIMIT 50— using the last seen row's key instead ofOFFSET, which forces the database to scan and discard skipped rows), and execute toggles as a single atomic conditional SQL update (UPDATE expenses SET is_reimbursed = NOT is_reimbursed WHERE id = :id AND amount_cents <= 100000 RETURNING *) so concurrent requests cannot race. - How would you design a tamper-evident audit trail recording every reimbursement status change and its actor? Create an append-only audit table (a table where application database roles have
INSERTandSELECTprivileges only, neverUPDATEorDELETE) such asexpense_audit_events(event_id, expense_id, actor_user_id, action, previous_state, new_state, occurred_at_utc, request_id). Insert the audit row inside the exact same database transaction (an all-or-nothing group of SQL writes that either commit together or roll back together) as theexpensesstatus update so an expense can never flip without recording a matching audit trail, and always readactor_user_idfrom the server-verified authentication token rather than client request parameters.
Follow-up questions
- What schema changes are needed to handle claims submitted in multiple currencies?
- Which relational database indexing and query strategies would keep this service fast across millions of records?
- How would you design a tamper-evident audit trail recording every reimbursement status change and its actor?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes