Detect Circular References in Nested Prefab Hierarchies

Last updated: November 29, 2026

Quick Overview

Prefabs can contain instances of other prefabs. Given a mapping from each prefab to the prefabs nested directly inside it, detect whether any circular nesting exists and return one cycle as a path, or None if the hierarchy is valid.

Unity
Coding & Algorithms
Software Engineer
Unity
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Prefabs can contain instances of other prefabs. Given a mapping from each prefab to the prefabs nested directly inside it, detect whether any circular nesting exists and return one cycle as a path, or None if the hierarchy is valid.

A natural Editor and asset pipeline question for Unity: an import step that recursively instantiates nested prefabs would recurse forever on a cycle. The interviewer looks for three-color DFS, an iterative version that will not overflow the stack on deep assets, and a useful error message.

What the Interviewer Expects
  • Model nesting as a directed graph
  • Use white/gray/black DFS to distinguish back edges from cross edges
  • Reconstruct and return the actual cycle path for the error message
  • Avoid recursion depth limits with an explicit stack
  • Include prefabs that appear only as children
Key Topics to Cover
graphs
DFS
cycle detection
topological order
asset pipelines
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you validate a single edit (adding one nested instance) without rescanning the whole project?
  • How would you also return a safe instantiation order when no cycle exists?
  • How do prefab variants (a prefab based on another) change the graph?
  • How would you report every cycle rather than just one?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: dict prefab -> [nested prefabs]. Output: a list like ['A','B','C','A'] showing one cycle, or None. Self-nesting (X contains X) counts. Children not present as keys are leaf prefabs. T...

High-Level Design

Run DFS with three colors: white (unvisited), gray (on the current path) and black (fully explored). An edge into a gray node is a back edge and proves a cycle; an edge into a black node is safe becau...


Submit Your Answer
Markdown supported

Related Questions