If you're traversing a graph that may contain cycles, what do you need to track, and what goes wrong if you don't?

technical-conceptual · Junior level · software-engineering

What the interviewer is really asking

Assesses whether the candidate understands why a visited set is mandatory on cyclic graphs, the failure mode without it, and the nuance of recursion-stack tracking for cycle detection in directed graphs.

What to say

What to avoid

Example answers

Strong: I track a visited set and skip any node already in it, because a graph — unlike a tree — can reach the same node through multiple edges. Without it, a cycle like A-B-A makes the traversal loop forever, and even an acyclic graph with shared subpaths gets re-explored, which can blow up to exponential time. So the visited set is what guarantees each node and edge is processed once, keeping it O(V + E).

Weak: As long as I don't immediately go back to the node I came from, I won't get stuck in a loop.

Want questions matched to your role? Paste a job title, job description, or CV and get a personalized set, or go Pro to unlock the full bank.