Professional Documents
Culture Documents
Interview Camp
Technique: Topological Sort
Level: Hard
Solution:
Topological sort is very useful in scheduling problems, or when you need to arrange a
graph in order. A topological sort is an ordering of nodes. We arrange nodes such that
for each node N, all its edges point to a node ahead of N.
You could use topological sort to solve several types of problems. For example, say that
you are given a graph of college classes. Each Node represents a class and each edge conveys
that a class is a prerequisite for another. You can use topological sort to calculate the
minimum number of semesters to complete the classes. Check out the video for more details.
You could also use it to find the longest path in a graph, which we will do in the homework
problems.
Note: Topological Sort is only possible if the Graph has no cycles.
It is also applicable only to directed graphs. In undirected graphs, every edge
can be considered a cycle since it points both ways.
To implement Topological sort, you simply add 1 line to Depth First Search (DFS).
At the end of the dfsVisit() function call, simply add the visited node to a stack.
At the end of the DFS, the stack will contain the nodes in topological order. Try it yourself
with examples.
Pseudocode:
dfsVisit(Node, Stack)
Node.state = VISITING
Node.state = VISITED
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
Stack.push(Node)
topoSort(Graph)
Stack = empty
for all nodes in Graph:
if node is UNVISITED, perform dfsVisit(node, Stack)
return Stack
Test Cases:
Edge Cases: empty graph, null graph
Base Cases: single node graph, 2 node graph, 2 node unconnected
Regular Cases: multiple nodes, multiple connected components
return stack;
}
node.setState(State.VISITED);
stack.push(node);
}
/*
* Helper Code. Ask interviewer before implementing.
*/
public enum State {
UNVISITED,
VISITING,
VISITED;
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
© 2017 Interview Camp (interviewcamp.io)