Bird
Raised Fist0

What is the time complexity of computing the cost() method when stacking k decorators on a core object using the Decorator Pattern with dynamic behavior injection?

medium🪤 Complexity Trap Q13 of Q15
OOP & Design Patterns - Decorator Pattern - Wrapping Behaviour Without Subclassing
What is the time complexity of computing the cost() method when stacking k decorators on a core object using the Decorator Pattern with dynamic behavior injection?
AO(1) because each decorator adds a fixed cost
BO(k) because each decorator delegates the call to the next one
CO(k^2) because each decorator calls all previous decorators recursively
DO(log k) because decorators form a balanced tree structure
Step-by-Step Solution
  1. Step 1: Identify call chain length

    Each decorator's cost() calls the wrapped object's cost(), forming a chain of length k.
  2. Step 2: Calculate total calls

    Cost computation requires traversing all k decorators once, so time complexity is O(k).
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Each decorator adds constant work, total linear in k [OK]
Quick Trick: Decorator calls chain length equals number of decorators [OK]
Common Mistakes:
MISTAKES
  • Assuming O(1) because cost is a simple addition
  • Mistaking recursive calls as quadratic
Trap Explanation:
PITFALL
  • O(1) looks plausible but ignores delegation chain; O(k^2) confuses recursion depth with repeated calls.
Interviewer Note:
CONTEXT
  • Checks understanding of delegation and call stack in decorator chains.
Master "Decorator Pattern - Wrapping Behaviour Without Subclassing" 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