Bird
Raised Fist0

If the Composite pattern iterator is extended to allow reusing leaf components multiple times during traversal (e.g., shared leaves), which modification is necessary to ensure correct iteration without infinite loops?

hard🎤 Interviewer Follow-up Q15 of Q15
OOP & Design Patterns - Iterator & Composite Pattern - Traversal Abstractions
If the Composite pattern iterator is extended to allow reusing leaf components multiple times during traversal (e.g., shared leaves), which modification is necessary to ensure correct iteration without infinite loops?
ANo change needed; the existing iterator handles reuse naturally.
BModify the iterator to push children in original order instead of reversed order.
CAdd a visited set to track and skip already visited components during iteration.
DConvert the iterator to a recursive traversal to handle reuse correctly.
Step-by-Step Solution
  1. Step 1: Understand reuse implications

    Reusing leaves means the same component can appear multiple times, risking infinite loops.
  2. Step 2: Identify solution to prevent infinite loops

    Tracking visited components prevents revisiting the same node repeatedly during iteration.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Visited set avoids infinite loops with shared components [OK]
Quick Trick: Track visited nodes to handle shared components safely [OK]
Common Mistakes:
MISTAKES
  • Assuming no changes needed
  • Changing push order does not fix reuse loops
Trap Explanation:
PITFALL
  • Candidates often overlook infinite loops caused by shared nodes without visited tracking.
Interviewer Note:
CONTEXT
  • Tests candidate's depth in handling iterator extensions and edge cases.
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