← Bytedance Interview Insights
This was a follow-up, so I was already mid-thought on something else when it landed.
Explain that DFS detects cycles by tracking nodes in the current recursion stack (for directed graphs) or by checking for visited neighbors that are not the parent (for undirected graphs). Then outline the algorithm: perform DFS, mark nodes as visited and in-stack, and if you encounter a node already in the stack, a cycle exists.
Pro tip: Clarify the distinction between directed and undirected graphs early, as the cycle detection logic differs; for directed graphs, use a recursion stack, while for undirected graphs, track the parent to avoid false positives from back-and-forth edges.
Ask whether the graph is directed or undirected, as the cycle detection approach varies. Mention that for directed graphs, a back edge to a node in the current recursion stack indicates a cycle, while for undirected graphs, a visited neighbor that is not the parent indicates a cycle.
Explain that you perform a depth-first search while maintaining two sets: one for all visited nodes and one for nodes currently in the recursion stack (for directed graphs). For undirected graphs, you only need a visited set and track the parent of each node.
During DFS, when exploring neighbors, if a neighbor is in the recursion stack (directed) or is visited and not the parent (undirected), a cycle is detected. Return true immediately.
Emphasize that you must run the DFS from every unvisited node to ensure all components are checked, as cycles may exist in disconnected parts of the graph.
State that time complexity is O(V+E) and space complexity is O(V) due to recursion stack and visited sets. Mention edge cases like self-loops and parallel edges.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.