Cart History: Undo and Redo Item Changes
Data Structure DesignAuto-graded · 22 test casesLast updated
Design a cart with reversible add/remove operations, tracking change history with undo/redo stacks.
Design a cart system that tracks items and supports reversible modifications.
Your cart maintains item identifiers mapped to their counts. Users can increase counts, decrease counts, reverse their last modification, or reapply a modification they just reversed.
Implement a function process_cart_operations(operations, arguments) that executes a sequence of cart commands:
"add_item"with arguments[item_id, quantity]: increases the count of the specified item by the given amount. If the item is not yet in the cart, this creates a new entry."remove_item"with arguments[item_id, quantity]: decreases the count of the specified item. If the count would reach zero, the item is deleted from the cart. If the requested amount exceeds the current count, the operation fails and the cart remains unchanged."undo"with arguments[]: reverses the most recent successful modification (add or remove) that has not already been reversed. If no such modification exists, the operation fails."redo"with arguments[]: reapplies the most recently reversed modification. If no modification has been reversed, or if a new add/remove has occurred since the last undo, the operation fails."items"with arguments[]: returns the current cart contents as a dictionary mapping item IDs to their counts.
The function returns a list of results, one per operation:
- For
"add_item"and"remove_item":Trueif successful,Falseif the operation failed - For
"undo"and"redo":Trueif successful,Falseif there was nothing to undo/redo - For
"items": a dictionary of the current cart state
When a new add or remove operation executes successfully, all previously reversed modifications become invalid and can no longer be redone.
Constraints
- Item identifiers are strings
- Quantities are positive integers (≥ 1)
- 1 ≤ number of operations ≤ 1000
- The history of modifications is unbounded
Examples
Example 1
Input: process_cart_operations(['add_item', 'add_item', 'items'], [['apple', 2], ['apple', 3], []])
Output: [True, True, {'apple': 5}]
Example 2
Input: process_cart_operations(['add_item', 'remove_item', 'items', 'undo', 'items', 'redo', 'items'], [['book', 4], ['book', 2], [], [], [], [], []])
Output: [True, True, {'book': 2}, True, {'book': 4}, True, {'book': 2}]
Example 3
Input: process_cart_operations(['remove_item', 'add_item', 'undo', 'redo', 'items'], [['missing', 1], ['pen', 1], [], [], []])
Output: [False, True, True, True, {'pen': 1}]
Example 4
Input: process_cart_operations(['add_item', 'add_item', 'undo', 'add_item', 'redo', 'items'], [['a', 1], ['b', 2], [], ['c', 3], [], []])
Output: [True, True, True, True, False, {'a': 1, 'c': 3}]
Hints
Hint 1
Maintain two stacks: one for modifications that can be reversed, and one for modifications that can be reapplied.
Hint 2
Each history entry needs to capture both the previous state and the new state of an item to allow bidirectional navigation.
Hint 3
When a new modification succeeds, clear the stack of reapplicable modifications since those changes are no longer part of the current timeline.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is maintaining bidirectional navigation through a modification timeline. We need to support both reversing changes and reapplying them, while ensuring that creating a new branch (by making a fresh modification after an undo) invalidates the abandoned timeline.
The solution uses two stacks to represent the timeline:
- An undo stack holds modifications that can be reversed, newest on top
- A redo stack holds modifications that were reversed and can be reapplied
Each history entry is a tuple capturing three pieces of information: the item identifier, its count before the change, and its count after the change. This representation allows us to move forward or backward through the timeline by applying the appropriate count.
For add and remove operations, we record the state transition and push it onto the undo stack. Critically, we clear the redo stack because any modifications that were undone are now unreachable—we've created a new timeline branch.
For undo, we pop from the undo stack, restore the old count, and push the entry onto the redo stack so it can be reapplied later.
For redo, we pop from the redo stack, reapply the new count, and push the entry back onto the undo stack since it's now part of the current timeline again.
Failed operations (like removing more items than exist) don't modify state and don't appear in history.
Why This Works
The stack structure naturally models the linear sequence of modifications. The newest change is always on top, and we can peel back changes one at a time. By storing both the before and after states, we can traverse in either direction without needing to recompute what the state should be.
Clearing the redo stack when a new modification occurs ensures correct behavior: once you make a new change after undoing, the old timeline is gone. This matches standard undo/redo semantics in editors and other tools.
Complexity
- Time: O(1) per operation. Each operation performs a constant amount of work—dictionary lookups, stack pushes/pops, and simple arithmetic.
- Space: O(n) where n is the number of successful modifications. Each modification stores one tuple in the history. The current cart state is O(m) where m is the number of distinct items.
Solution
from typing import List
def process_cart_operations(operations: List[str], arguments: List[List]) -> List:
cart = {}
undo_stack = []
redo_stack = []
result = []
for operation, args in zip(operations, arguments):
if operation == "add_item":
item_id, quantity = args
old_quantity = cart.get(item_id, 0)
cart[item_id] = old_quantity + quantity
undo_stack.append((item_id, old_quantity, old_quantity + quantity))
redo_stack.clear()
result.append(True)
elif operation == "remove_item":
item_id, quantity = args
old_quantity = cart.get(item_id, 0)
if old_quantity < quantity:
result.append(False)
continue
new_quantity = old_quantity - quantity
if new_quantity == 0:
del cart[item_id]
else:
cart[item_id] = new_quantity
undo_stack.append((item_id, old_quantity, new_quantity))
redo_stack.clear()
result.append(True)
elif operation == "undo":
if not undo_stack:
result.append(False)
continue
item_id, old_quantity, new_quantity = undo_stack.pop()
if old_quantity == 0:
cart.pop(item_id, None)
else:
cart[item_id] = old_quantity
redo_stack.append((item_id, old_quantity, new_quantity))
result.append(True)
elif operation == "redo":
if not redo_stack:
result.append(False)
continue
item_id, old_quantity, new_quantity = redo_stack.pop()
if new_quantity == 0:
cart.pop(item_id, None)
else:
cart[item_id] = new_quantity
undo_stack.append((item_id, old_quantity, new_quantity))
result.append(True)
elif operation == "items":
result.append(dict(cart))
return result