Topological Sorting
Topological Sorting
1. Basics
(1) Topological Sorting By Breath First Search (Kahn's Algorithm)
Idea:
Create adjacent list for the graph
Calculate the inDegree for each node
Start with node with 0 inDegree and do BFS for its neighbor
Everytime we visit a node, we decrement the inDegree of it by 1, if the inDegree turns to 0, we add the node to queue
(2) Topological Sorting By Depth First Search
ideas:
Create adjacent list for the graph
Maintain two boolean array visited and visiting, where visited mean a node has been visited from a path in dfs, while visiting means a node is being visited in the dfs
If the visiting value for a node is true, this means a loop is found
If the visited value for a node is true, this means we have visited this node, we can skip it
2. Thoughts
Q:What if the input is not integer, but rather character or string, what data structure should we use to build up adjacent list and inDegree?
A: Use hashmap, for example, if the input is character, then Adjacent list: Map<Character, Set<Character>>, inDegree: Map<Character, Integer>
Q: Time Complexity for Topological Sort:
A: O(n + e), where n is the number of nodes and e is the number of edges
3. Interview Questions
Last updated
Was this helpful?