Bird
Raised Fist0

What is the time complexity per operation (execute, undo, or redo) in the brute force Command Pattern implementation that uses manual undo and redo stacks for n commands?

medium🪤 Complexity Trap Q13 of Q15
OOP & Design Patterns - Command Pattern - Undo/Redo, Request Queuing & Logging
What is the time complexity per operation (execute, undo, or redo) in the brute force Command Pattern implementation that uses manual undo and redo stacks for n commands?
AO(n) because undo requires scanning the entire stack to find the last command.
BO(n) due to copying the entire command history on each operation.
CO(log n) due to balancing the undo and redo stacks.
DO(1) because each operation involves only stack push/pop and a single command execution or undo.
Step-by-Step Solution
Solution:
  1. Step 1: Identify operations involved per command

    Each execute, undo, or redo involves pushing or popping a command from a stack and calling execute or undo on that command.
  2. Step 2: Analyze time per operation

    Stack push/pop and command execute/undo are O(1) operations, so total per operation is O(1).
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Stacks and command calls are constant time [OK]
Quick Trick: Undo/redo stacks enable O(1) per operation [OK]
Common Mistakes:
MISTAKES
  • Assuming undo scans entire history
  • Confusing stack operations with linear scans
Trap Explanation:
PITFALL
  • Many think undo requires scanning or copying stacks, but stacks allow O(1) push/pop.
Interviewer Note:
CONTEXT
  • Tests understanding of data structure operations and their impact on complexity.
Master "Command Pattern - Undo/Redo, Request Queuing & Logging" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes