Bird
Raised Fist0

When implementing a prototype pattern for cloning an object graph containing cyclic references, which technique best prevents infinite recursion during deep copy?

hard🔁 Follow-up Q10 of Q15
OOP & Design Patterns - Prototype Pattern - Deep Copy vs Shallow Copy
When implementing a prototype pattern for cloning an object graph containing cyclic references, which technique best prevents infinite recursion during deep copy?
AUse a global variable to track copied objects.
BMaintain a memo dictionary mapping original objects to their copies.
CAvoid copying nested objects and only copy top-level fields.
DUse shallow copy instead of deep copy to prevent recursion.
Step-by-Step Solution
Solution:
  1. Step 1: Understand cyclic references problem

    Deep copying objects with cycles can cause infinite recursion if the same object is copied repeatedly.
  2. Step 2: Use memoization

    Maintaining a memo dictionary that maps original objects to their copies prevents re-copying and breaks recursion.
  3. Step 3: Evaluate options

    A global variable is not thread-safe or sufficient; avoiding nested copies loses data; shallow copy doesn't clone nested objects.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Memo dict prevents infinite recursion in cyclic graphs [OK]
Quick Trick: Memo dict tracks copied objects to avoid recursion [OK]
Common Mistakes:
MISTAKES
  • Using shallow copy which doesn't clone nested objects
  • Relying on global variables which are error-prone
  • Skipping nested objects leading to incomplete copies
Trap Explanation:
PITFALL
  • Option A seems correct but lacks proper object-to-copy mapping; shallow copy misses nested objects.
Interviewer Note:
CONTEXT
  • Tests knowledge of handling cyclic references in deep copy implementations.
Master "Prototype Pattern - Deep Copy vs Shallow Copy" 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