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 result
  • SUBTRACT - Subtract a number from current result
  • MULTIPLY - Multiply current result by a number
  • DIVIDE - Divide current result by a number
  • UNDO - Undo the last operation
  • REDO - 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
Command Pattern CalculatorINPUT COMMANDSCOMMAND PATTERNFINAL RESULT["ADD", "10"]["MULTIPLY", "2"]["UNDO"]["ADD", "5"]1Create Command Objects2Execute & Push to Stack3Undo: Pop & Reverse4Continue ProcessingUndo Stack[AddCmd(5)]15Final calculator resultafter all operationsKey Insight:Command objects encapsulate both execution and undo logic, enabling O(1) undo/redo operationsinstead of replaying all operations from the beginning.TutorialsPoint - Command Pattern Calculator | Optimized Solution
Asked in
Google 42 Microsoft 38 Amazon 35 Adobe 28
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen