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 at 1 (1, 2, 3, ...). Rejected creation requests do not consume an ID, deleted IDs are never reused, and any caller-provided id in an input payload must be ignored.
  • amount (float or int): a strictly positive, finite numeric charge (bool values are invalid even though bool subclasses int in Python).
  • category (str): a label for the spend type, defaulting to "" when omitted.
  • is_reimbursed (bool): whether payout has occurred; always starts as False upon 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]): Check expense_data.get("amount"). If it is missing, a boolean, non-numeric, non-finite (NaN or 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 with id == expense_id and 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 that expense_id exists; if not, return {"error": "expense not found"}. Next enforce the high-value cap: if the record has amount > 1000, leave is_reimbursed unchanged and return {"error": "approval required"} (amounts <= 1000, including 1000, may be toggled freely). Otherwise flip is_reimbursed between False and True and 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 operations is one of "add_expense", "delete_expense", "list_expenses", or "toggle_reimbursement".
  • Single-record operations (add_expense, delete_expense, toggle_reimbursement) should run in expected O(1) time, and list_expenses should run in O(n) time for n active records.
  • Existence is checked before the 1000 approval limit in toggle_reimbursement.

Step-by-step walkthrough

  1. 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_expenses returns 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 with amount <= 0 (or non-numeric input),
      • "expense not found" when deleting or toggling a missing ID,
      • "approval required" when toggling an expense whose amount > 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
    
  2. Model `Expense` and pick an O(1) storage structure

    Every single-item operation (delete_expense, toggle_reimbursement) looks up an expense by id. If we stored expenses in a plain Python list, every lookup or deletion would scan up to n items (O(n)). Instead, we store them in a dictionary self.expenses: Dict[int, Expense] keyed by id:

    • Lookup and deletion by id take O(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 Expense with @dataclass (a standard Python decorator that auto-generates __init__, __repr__, and equality checks from field type annotations) and define a custom ExpenseError(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
    
  3. Validate amounts safely and assign monotonic IDs

    When adding an expense, three subtle bugs often trip people up in backend interviews:

    1. Python booleans are integers: isinstance(True, int) is True in Python (True == 1), so a naive isinstance(val, (int, float)) and val > 0 accidentally accepts amount = True as $1! We reject bool first and use math.isfinite(value) to reject NaN and inf.
    2. Never trust client-supplied id or is_reimbursed: If we unpacked Expense(**expense_data), a caller could submit {"amount": 5000, "is_reimbursed": True} and bypass the $1,000 approval limit. Always set id = self.next_id and is_reimbursed = False on the server.
    3. Use a monotonic counter (self.next_id), incremented only on success: Computing IDs as len(self.expenses) + 1 reuses old IDs after a deletion, causing receipts or audit links to point at the wrong expense. And incrementing self.next_id after 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
    
  4. Order checks carefully in `delete` and `toggle`

    Both delete_expense and toggle_reimbursement must verify that expense_id exists 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_reimbursed
    

    Notice the boundary expense.amount > APPROVAL_LIMIT (> 1000, not >= 1000): the rule says "greater than $1,000", so an expense of exactly 1000 can 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 expense
    
  5. Return fresh dict snapshots in the driver

    Why do we convert every returned Expense with asdict(...) inside _execute_operation instead of storing dicts and returning them directly?

    Suppose list_expenses() runs at Step 2 when is_reimbursed is False, and toggle_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 in results would silently flip to True! Calling asdict(expense) creates an independent snapshot (a fresh dictionary copy) on every call.

    We also catch only ExpenseError in manage_expenses so genuine bugs like an unknown operation name (ValueError) still surface immediately instead of masquerading as user errors.

  6. 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}]
    
  7. 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 single O(1) average hash-map lookup/insert/delete on self.expenses, and copies a fixed 5-field Expense dataclass (a lightweight Python class generated from field annotations) into a dict via asdict.
    • list_expenses: O(n). Iterating over all n stored expenses and serializing each into a fresh dictionary copy does constant work per stored expense.
  • Space: O(n). self.expenses stores one Expense instance per active expense, and each list_expenses() response allocates an O(n) list of snapshot dicts.

Edge cases

  • Zero, negative, boolean, or NaN amounts: 0, -5, True (which subclasses int in Python!), float("nan"), and float("inf") are all rejected with "amount must be greater than zero" without advancing self.next_id.
  • Exact $1,000 approval boundary: amount = 1000 satisfies not (1000 > 1000) and toggles cleanly; amount = 1000.01 raises "approval required" and leaves is_reimbursed unchanged.
  • 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 had amount = 2000, toggling its old ID reports "expense not found" (not "approval required") because existence is checked first.
  • ID non-reuse: Deleting ID 2 never re-issues ID 2; the next valid add_expense receives ID 3.
  • Server-controlled fields: Client-supplied id or is_reimbursed: True inside expense_data are ignored so callers cannot forge IDs or pre-approve high-value expenses.
  • Toggling twice: Flipping not expense.is_reimbursed a second time cleanly restores False.

Common mistakes

  • Generating IDs with len(self.expenses) + 1: Adding two items (id=1, 2), deleting id=1 (len=1), and adding a third produces len + 1 = 2, overwriting the still-existing id=2!
  • Incrementing next_id before validating amount: A rejected negative expense burns an ID and leaves confusing gaps during testing.
  • Checking amount > 1000 before checking whether the expense exists, or mutating before checking: Always look up first, validate rules second, and mutate state last.
  • Writing >= 1000 instead of > 1000: The business rule restricts amounts strictly greater than $1,000.
  • Returning live references instead of copies: Appending internal mutable dicts directly into results causes later toggle_reimbursement calls to mutate earlier list_expenses outputs.
  • Catching bare Exception in the driver: Catching everything turns genuine code bugs (NameError, TypeError, unknown operation names) into {"error": ...} dicts instead of failing loudly; catch only ExpenseError.
  • Using binary float for money in production: In IEEE-754 floating point, 0.1 + 0.2 == 0.30000000000000004. Real financial systems store integer cents (5000 for $50.00) or decimal.Decimal.

Alternative approaches

  • Mapping ExpenseManager to HTTP REST endpoints: In a web service, the exact same ExpenseManager methods 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 as 2 decimal places / cents for USD vs 0 decimal places for JPY) or Decimal rather than float. Because the $1,000 approval threshold is defined in the company's base currency (say USD), also record exchange_rate_to_base and base_amount_cents at 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 id as the B-tree primary key for O(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 a WHERE filter, such as CREATE INDEX ... ON expenses(created_at) WHERE is_reimbursed = FALSE, keeping the index tiny once most historical expenses are paid). Replace unbounded list_expenses() with keyset pagination (WHERE id < :cursor ORDER BY id DESC LIMIT 50 — using the last seen row's key instead of OFFSET, 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 INSERT and SELECT privileges only, never UPDATE or DELETE) such as expense_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 the expenses status update so an expense can never flip without recording a matching audit trail, and always read actor_user_id from the server-verified authentication token rather than client request parameters.

Follow-up questions

Similar questions

More Color Health interview questions

All 1 Color Health questions →