Expense Reimbursement Ledger Simulator
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate an expense tracking ledger executing sequential API calls with validation and error checks.
Design an in-memory expense tracking module that processes a series of ledger commands.
Each operation is passed as a string command name with a corresponding list of arguments. You will execute the operations sequentially and return a list containing the output of each operation.
Data Model
An expense dictionary contains the following fields:
id(int): Unique identifier assigned sequentially starting at 1.amount(floatorint): Numerical value of the expense.category(str): Category label.description(str): Brief description.is_reimbursed(bool): Reimbursement status (defaults toFalse).
Operations & Rules
-
"add_expense": Takes a payload dictionary[data].- Rule: If
data["amount"] <= 0, do not create an expense. Append{"error": "amount must be greater than zero"}to the result. - If valid, assign a unique
idstarting from 1 (incrementing by 1 for each successful addition). Setis_reimbursedtodata.get("is_reimbursed", False). - Store a copy of the new record and append a copy of it to the result.
- Rule: If
-
"delete_expense": Takes an[expense_id].- If
expense_idis not present in the system, append{"error": "expense not found"}. - Otherwise, remove the record from the system and append
Noneto the result.
- If
-
"list_expenses": Takes an empty argument list[].- Returns a list of all active expenses ordered by their
idin ascending order. Append this list to the result.
- Returns a list of all active expenses ordered by their
-
"toggle_reimbursement": Takes an[expense_id].- If
expense_idis not present in the system, append{"error": "expense not found"}. - Rule: If the expense exists but has
amount > 1000, do not toggle its status. Append{"error": "approval required"}. - If valid, flip the boolean
is_reimbursedvalue for that expense and append a copy of the updated expense to the result.
- If
-
Any unrecognized operation name: Append
{"error": "unknown operation"}.
Constraints
- $1 \le \text{len(operations)} \le 1000$
operations[i]matches one of the operation strings described above.arguments[i]contains the matching arguments foroperations[i].- Expense amounts are finite numbers.
Edge Case Notes
- Rejected
add_expensecalls do not increment the ID counter. - IDs are persistent and are never reused, even after deletion.
Examples
Example 1
Input: manage_expenses(['add_expense', 'toggle_reimbursement', 'list_expenses'], [[{'amount': 50, 'category': 'Travel', 'description': 'Uber'}], [1], []])
Output: [{'id': 1, 'amount': 50, 'category': 'Travel', 'is_reimbursed': False, 'description': 'Uber'}, {'id': 1, 'amount': 50, 'category': 'Travel', 'is_reimbursed': True, 'description': 'Uber'}, [{'id': 1, 'amount': 50, 'category': 'Travel', 'is_reimbursed': True, 'description': 'Uber'}]]
Example 2
Input: manage_expenses(['add_expense', 'add_expense', 'toggle_reimbursement', 'delete_expense', 'list_expenses'], [[{'amount': 1250, 'category': 'Equipment', 'description': 'Monitor'}], [{'amount': -5, 'category': 'Meals', 'description': 'Lunch'}], [1], [9], []])
Output: [{'id': 1, 'amount': 1250, 'category': 'Equipment', 'is_reimbursed': False, 'description': 'Monitor'}, {'error': 'amount must be greater than zero'}, {'error': 'approval required'}, {'error': 'expense not found'}, [{'id': 1, 'amount': 1250, 'category': 'Equipment', 'is_reimbursed': False, 'description': 'Monitor'}]]
Hints
Hint 1
Use a hash map (dictionary) keyed by `id` to store active expenses for O(1) retrieval, deletion, and updates.
Hint 2
Maintain a separate integer variable for `next_id` starting at 1 that increments only upon successful creation of an expense.
Hint 3
Always return copies of stored dictionaries when appending to the output list to prevent unwanted mutation side effects.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to design an stateful expense tracking system that processes sequential operations.
We can maintain:
expenses: A hash map mapping anidto its expense record dictionary.next_id: An integer initialized to 1 tracking the next unique ID.results: A list to store the output of each command in order.
For each operation in the input:
add_expense: Validate thatamount > 0. If invalid, return an error dictionary. If valid, build the expense record withid = next_id, incrementnext_id, store it inexpenses, and append a copy of the dictionary toresults.delete_expense: Check ifexpense_idexists inexpenses. If missing, return an error dictionary. Otherwise, delete the key fromexpensesand appendNonetoresults.list_expenses: Collect copies of all stored expenses ordered by key (id) and append the list toresults.toggle_reimbursement: Check ifexpense_idexists. If missing, return error"expense not found". Ifamount > 1000, return error"approval required". Otherwise, negateis_reimbursedin place and append a copy of the updated dictionary toresults.- Unrecognized operations: Append
{"error": "unknown operation"}.
Complexity
- Time Complexity:
add_expense,delete_expense,toggle_reimbursement: $\mathcal{O}(1)$ average time per call.list_expenses: $\mathcal{O}(N \log N)$ per call to sort $N$ active IDs (or $\mathcal{O}(N)$ if relying on dictionary key order).- Overall time for $M$ operations: $\mathcal{O}(M \cdot N \log N)$ worst-case.
- Space Complexity: $\mathcal{O}(N)$ where $N$ is the number of active stored expenses.
Python Reference Solution
from typing import Dict, List, Any
def manage_expenses(operations: List[str], arguments: List[List[Any]]) -> List[Any]:
expenses: Dict[int, Dict[str, Any]] = {}
next_id = 1
results: List[Any] = []
for operation, args in zip(operations, arguments):
if operation == "add_expense":
data = args[0]
amount = data["amount"]
if amount <= 0:
results.append({"error": "amount must be greater than zero"})
continue
expense = {
"id": next_id,
"amount": amount,
"category": data["category"],
"is_reimbursed": data.get("is_reimbursed", False),
"description": data["description"],
}
expenses[next_id] = expense
next_id += 1
results.append(expense.copy())
elif operation == "delete_expense":
expense_id = args[0]
if expense_id not in expenses:
results.append({"error": "expense not found"})
else:
del expenses[expense_id]
results.append(None)
elif operation == "list_expenses":
results.append([expenses[key].copy() for key in sorted(expenses)])
elif operation == "toggle_reimbursement":
expense_id = args[0]
if expense_id not in expenses:
results.append({"error": "expense not found"})
elif expenses[expense_id]["amount"] > 1000:
results.append({"error": "approval required"})
else:
expenses[expense_id]["is_reimbursed"] = not expenses[expense_id]["is_reimbursed"]
results.append(expenses[expense_id].copy())
else:
results.append({"error": "unknown operation"})
return results