Bird
Raised Fist0

Examine the following buggy CompositeIterator code snippet. Which line contains the subtle bug that causes incorrect traversal order?

medium🐞 Bug Identification Q14 of Q15
OOP & Design Patterns - Iterator & Composite Pattern - Traversal Abstractions
Examine the following buggy CompositeIterator code snippet. Which line contains the subtle bug that causes incorrect traversal order?
ALine initializing self.stack without reversing children.
BLine checking hasNext() before popping from stack.
CLine popping component from stack.
DLine returning the component after processing.
Step-by-Step Solution
  1. Step 1: Identify stack initialization issue

    Stack is initialized with children in original order, not reversed, causing traversal order reversal.
  2. Step 2: Confirm impact on traversal order

    Without reversing, popping from stack yields children in reverse order, breaking expected traversal.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Reversing children on stack initialization fixes traversal order [OK]
Quick Trick: Stack must reverse children to preserve traversal order [OK]
Common Mistakes:
MISTAKES
  • Forgetting to reverse children on stack push
  • Misplacing hasNext() check
Trap Explanation:
PITFALL
  • Not reversing children is subtle and causes reversed traversal order, often overlooked.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to spot subtle iterator implementation bugs affecting order.
Master "Iterator & Composite Pattern - Traversal Abstractions" 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