Professional Documents
Culture Documents
Interview Camp
Technique: Detecting Cycles using DFS
Level: Medium
Questions to Clarify:
Q. Is this a directed or undirected graph?
A. It is a directed graph.
Solution:
We do a Depth First Search (DFS). During the DFS, we visit nodes. This involves going through the
node's neighbors.
While visiting a node N, let's say we find that one of N's neighbors - P - is already in the VISITING state.
This means P is in the path from root to N, which means we have found a cycle. P and N are part of this
cycle.
Note that we look for neighbors in the VISITING state and not VISITED state. This is because if a
neighbor X has been visited already, we have processed all the nodes from X, and there is no path
from X to N.
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
Pseudocode:
Node.state = VISITED
Target not found, return false
Test Cases:
Edge Cases: Empty graph
Base Cases: 1 node, 2 nodes connected/disconnected
Regular Cases: Has cycle, No cycle
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
node.setState(State.VISITED);
return false;
}
/*
* Helper Code. Ask interviewer before implementing.
*/
public enum State {
UNVISITED,
VISITING,
VISITED;
}
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
© 2017 Interview Camp (interviewcamp.io)