Bird
Raised Fist0

If an object is wrapped by k decorators, each adding a constant time operation in the cost() method, what is the overall time complexity of calling cost() on the outermost decorator?

medium🧾 Code Tracing Q5 of Q15
OOP & Design Patterns - Decorator Pattern - Wrapping Behaviour Without Subclassing
If an object is wrapped by k decorators, each adding a constant time operation in the cost() method, what is the overall time complexity of calling cost() on the outermost decorator?
AO(1)
BO(k)
CO(k^2)
DO(log k)
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the call chain

    Each decorator calls cost() on the wrapped object, adding constant time.
  2. Step 2: Calculate total time

    With k decorators, calls chain linearly, so total time is proportional to k.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Each decorator adds constant time, calls chain linearly [OK]
Quick Trick: Decorator calls chain linearly, so time is O(k) [OK]
Common Mistakes:
MISTAKES
  • Assuming constant time ignoring the chain of calls.
  • Mistaking it for O(k^2) by double counting.
  • Thinking logarithmic due to recursion, which is incorrect here.
Trap Explanation:
PITFALL
  • Ignoring the recursive call chain leads to underestimating time complexity.
Interviewer Note:
CONTEXT
  • Tests understanding of performance implications of stacked decorators.
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