Professional Documents
Culture Documents
Interview Camp
Technique: Depth First Search (DFS)
Level: Medium
Solution:
DFS is extremely common. You won’t be asked to implement it directly. You’ll typically be given a
problem that can be modeled as a graph.
Tip: You should practice this code at least 3 times to get familiar with it.
When you think of Depth First Search, you should immediately think of the dfsVisit() function.
This function checks if the current node is equal to the target, and then visits its neighbors.
For DFS, it is standard for each node to have a State - UNVISITED, VISITING and VISITED. We store
that state as the Node’s property.
If we cannot add a property to the Node class (not typical), we can also maintain a list
that maps the node to its state. Usually, the interviewer is ok with keeping it as a node-level property.
dfsVisit() function does the following:
dfsVisit(Node)
mark Node VISITING
process node
Run dfsVisit() on each unvisited neighbor
mark Node VISITED
For this problem, the "process node" part will be - checking if the data in this node is equal to target,
and returning true if so.
Typically in interviews, you are given an entry-point into the graph. This will be a Node. You can use this
node to start your search.
However, that depends entirely on the problem. If the problem graph has multiple connected
components, you will need an entry point into each component.
For the sake of simplicity, we’ll assume we have a Graph class with a list of nodes. We will run dfsVisit()
on all UNVISITED nodes of the graph. This is because there might be multiple connected components in
the graph, and we want to cover all of them.
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
Pseudocode:
dfsVisit(Node, Target)
Node.state = VISITING
if (Node.data = Target)
return true;
Node.state = VISITED
Target not found, return false
dfs(Graph, Target)
for all nodes in Graph:
if node is UNVISITED, perform dfsVisit
if dfsVisit returned true, Target found, return true
Target not found, return false
Test Cases:
Edge Cases: empty graph, null graph
Base Cases: Graph with 1 node, graph with 2 nodes, graph with 2 disconnected nodes
Regular Cases: Target in graph/not in graph, Target first element/deep in graph
if (node.getData() == target)
return true;
© 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)