KatInterview

Reversible Wallet Balance Tracker with Undo and Redo

Data Structure DesignModel answer
MediumModel answerData Structure Designdesignundo-redostacks

Last 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. Raises ValueError if starting_cents is negative.
  • apply_change(cents: int) -> int: adds cents (positive or negative) to the balance. If the result would be below zero, the call is rejected: raise ValueError and leave everything unchanged. On success, discard any redo history and return the new balance.
  • reset_to(target_cents: int) -> int: sets the balance directly to target_cents. Raises ValueError if target_cents is negative (no state change). On success, discard any redo history and return the new balance.
  • undo() -> bool: reverses the most recent successful mutation (either apply_change or reset_to). Returns True if something was reversed, otherwise False.
  • redo() -> bool: re-applies the most recently undone mutation. Returns True if something was re-applied, otherwise False.
  • 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^12 at all times
  • -10^10 <= cents <= 10^10
  • At most 10^5 method 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.