Reversible Wallet Balance Tracker with Undo and Redo
Data Structure DesignModel answerLast updated
Design an in-memory wallet class that applies relative changes and absolute resets to an integer-cent balance, with full undo and redo and constant-time operations.
Reversible Wallet Balance Tracker
You are building a small in-memory component that tracks a customer's prepaid wallet. Money is stored as an integer number of cents, never as a float, so every result is exact. The component must keep a complete, reversible history of changes so that mistakes can be rolled back and re-applied.
Design a class Wallet with these methods:
__init__(starting_cents: int = 0): creates the wallet. RaisesValueErrorifstarting_centsis negative.apply_change(cents: int) -> int: addscents(positive or negative) to the balance. If the result would be below zero, the call is rejected: raiseValueErrorand leave everything unchanged. On success, discard any redo history and return the new balance.reset_to(target_cents: int) -> int: sets the balance directly totarget_cents. RaisesValueErroriftarget_centsis negative (no state change). On success, discard any redo history and return the new balance.undo() -> bool: reverses the most recent successful mutation (eitherapply_changeorreset_to). ReturnsTrueif something was reversed, otherwiseFalse.redo() -> bool: re-applies the most recently undone mutation. ReturnsTrueif something was re-applied, otherwiseFalse.balance() -> int: returns the current balance in cents.
Every method must run in O(1) time.
Example
w = Wallet(100)
w.apply_change(50) # balance 150
w.reset_to(300) # balance 300
w.apply_change(-100) # balance 200
w.undo() # True, balance 300
w.undo() # True, balance 150
w.redo() # True, balance 300
w.apply_change(20) # balance 320, redo history is now discarded
w.redo() # False
w.balance() # 320
Constraints
0 <= balance <= 10^12at all times-10^10 <= cents <= 10^10- At most
10^5method calls in total - The balance may never go below
0
What to cover in your answer
Describe your data structures, explain why undo works for reset_to even though it loses information, justify the O(1) claim honestly, and list the edge cases you would test.
Hints
Hint 1
A relative change can be reversed by subtracting it, but a direct reset cannot be reversed from its argument alone. What extra information must you remember?
Hint 2
Instead of storing operation-specific inverse logic, store each mutation as a pair of absolute balances: the one before and the one after. Undo and redo then become plain assignments.
Hint 3
Use two stacks, one for undo and one for redo. Think carefully about when the redo stack must be cleared, and whether a rejected call should clear it.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the command pattern with two stacks, and the key decision is what each history record stores.
The two mutations invert differently. A relative change apply_change(d) can be undone by applying -d, but reset_to(x) overwrites the old value, so x alone cannot tell you what to restore. Rather than writing separate inverse logic per operation, store a state transition for every successful mutation:
(prev_balance, new_balance)
Optionally add an operation tag and the original argument for auditing, but undo and redo never need them.
Data structures
balance: the current integer cents.undo_stack: transitions that led to the current state, oldest at the bottom.redo_stack: transitions that were undone and can be re-applied.
Operations
- Mutation (
apply_change/reset_to): compute the candidate balance and validate first. If it is invalid, raise without touching anything. Otherwise record(balance, candidate), push it onundo_stack, setbalance = candidate, and clearredo_stack. undo: ifundo_stackis empty returnFalse. Otherwise pop a record, setbalance = record.prev, push the record onredo_stack, returnTrue.redo: ifredo_stackis empty returnFalse. Otherwise pop a record, setbalance = record.new, push it onundo_stack, returnTrue.balance: return the field.
Why it is correct
Invariant: the top of undo_stack has new == balance, and the top of redo_stack has prev == balance.
- A successful mutation creates a record that satisfies the invariant. Previously undone records describe a future that no longer exists, so discarding them is the correct "branch invalidation".
- Undo and redo restore stored absolute values. No arithmetic is recomputed, so there is no drift, and
reset_tois handled for free. - Redo needs no re-validation: each stored balance was already checked to be non-negative when first produced.
- Validate before mutate. A rejected call changes no field and does not clear the redo stack, because no successful forward action occurred.
Complexity
undo,redo,balance: worst-caseO(1).- Mutations:
O(1)amortized. Clearing the redo stack costsO(k), but each record enters the redo stack only through anundo, so every clear is paid for by earlier undos. Total work overncalls isO(n). - If worst-case
O(1)is required, use one list with acursorand atopindex. A new mutation writes athistory[cursor], incrementscursor, and setstop = cursor, lazily truncating the redo branch. Undo decrementscursor, and redo is valid whilecursor < top. - Space:
O(n)records, at most about10^5.
Code
from typing import List, NamedTuple
class _Step(NamedTuple):
op: str # "change" or "reset", kept for auditing
arg: int # the argument as supplied
prev: int # balance before
new: int # balance after
class Wallet:
def __init__(self, starting_cents: int = 0) -> None:
if starting_cents < 0:
raise ValueError("starting balance cannot be negative")
self._bal = starting_cents
self._undo: List[_Step] = []
self._redo: List[_Step] = []
def _commit(self, op: str, arg: int, new_bal: int) -> int:
self._undo.append(_Step(op, arg, self._bal, new_bal))
self._bal = new_bal
self._redo.clear()
return self._bal
def apply_change(self, cents: int) -> int:
new_bal = self._bal + cents
if new_bal < 0:
raise ValueError("balance would become negative")
return self._commit("change", cents, new_bal)
def reset_to(self, target_cents: int) -> int:
if target_cents < 0:
raise ValueError("balance cannot be negative")
return self._commit("reset", target_cents, target_cents)
def undo(self) -> bool:
if not self._undo:
return False
step = self._undo.pop()
self._bal = step.prev
self._redo.append(step)
return True
def redo(self) -> bool:
if not self._redo:
return False
step = self._redo.pop()
self._bal = step.new
self._undo.append(step)
return True
def balance(self) -> int:
return self._bal
Tracing the example
Start at 100. apply_change(50) gives 150, reset_to(300) gives 300, apply_change(-100) gives 200. Two undos give 300 then 150. Redo gives 300. apply_change(20) gives 320 and clears the redo stack, so redo() returns False and balance() is 320.
Edge cases to test
undoorredoon empty history returnsFalseand changes nothing.- A change landing exactly on 0 is allowed; going below 0 raises with no state change.
- A rejected call must not clear redo history.
apply_change(0)and resetting to the current balance are still recorded as mutations, since they are real events in an audit trail and must be undoable.- Undo past a reset, then a new change:
redoreturnsFalse. - Negative starting balance or negative reset target raises.
- Integer overflow is not a concern in Python; in fixed-width languages,
10^12 + 10^10still fits in 64 bits.
Common mistakes
- Undoing a reset by "subtracting" something, which is impossible without the old value.
- Storing only deltas and recomputing on redo, which invites drift and re-validation bugs.
- Clearing the redo stack before validation, so a failed call destroys history.
- Claiming strict worst-case
O(1)for mutations without acknowledging the amortized clear. - Using floats for money.
Follow-ups worth discussing
- Concurrency: serialize operations per account via a single owner (actor or partition) or a per-account lock. In a database, use optimistic concurrency with a version column and compare-and-swap.
- Idempotency: clients send an idempotency key, and the server stores the key with its result in the same transaction as the mutation so retries do not apply twice.
- Memory bounds: cap history length, or persist an append-only log and snapshot periodically.