Command Pattern Calculator - Problem
Design and implement a calculator using the Command Pattern that supports basic arithmetic operations with undo and redo functionality.
Your calculator should support the following operations:
ADD- Add a number to current resultSUBTRACT- Subtract a number from current resultMULTIPLY- Multiply current result by a numberDIVIDE- Divide current result by a numberUNDO- Undo the last operationREDO- Redo the last undone operation
Each operation is represented as a string array: ["ADD", "5"] or ["UNDO"]
The calculator starts with a result of 0. Return the final result after executing all commands.
Input & Output
Example 1 — Basic Operations with Undo
$
Input:
commands = [["ADD", "10"], ["MULTIPLY", "2"], ["UNDO"], ["ADD", "5"]]
›
Output:
15
💡 Note:
Start: 0 → ADD 10: 10 → MULTIPLY 2: 20 → UNDO: 10 → ADD 5: 15
Example 2 — Undo and Redo Operations
$
Input:
commands = [["ADD", "8"], ["SUBTRACT", "3"], ["UNDO"], ["REDO"]]
›
Output:
5
💡 Note:
Start: 0 → ADD 8: 8 → SUBTRACT 3: 5 → UNDO: 8 → REDO: 5
Example 3 — Multiple Undos
$
Input:
commands = [["ADD", "12"], ["DIVIDE", "3"], ["MULTIPLY", "5"], ["UNDO"], ["UNDO"]]
›
Output:
4
💡 Note:
Start: 0 → ADD 12: 12 → DIVIDE 3: 4 → MULTIPLY 5: 20 → UNDO: 4 → UNDO: 12
Constraints
- 1 ≤ commands.length ≤ 1000
- Each operation value is between -1000 and 1000
- Division by zero will not occur
- UNDO will only be called when there are operations to undo
- REDO will only be called when there are operations to redo
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code