Reference Cycles and the Garbage Collector

Talk it through out loud with your AI coach.

The problem

  • medium
  • Pro

In a tree structure, each node keeps a list of its children and each child keeps a reference back to its parent. An interviewer asks whether these nodes are ever freed once your code stops using the tree. Explain how Python handles reference cycles.

What a strong answer covers

  • Why mutual references defeat simple counting.
  • The extra mechanism CPython uses to find unreachable groups.
  • What that costs compared with immediate freeing.
  • How to design the structure so the problem doesn't arise.

Common mistake: Saying the nodes leak forever, ignoring the cycle collector, or saying Python has only a tracing garbage collector like Java.

Knowing this is half of it. Saying it clearly out loud is the part the coach helps you practise.

Practise it out loud