Graph algorithms
These are the graph algorithms that are common in coding interviews.
Topological sort. O(V + E) time.
Given a directed graph, put its nodes in an order where every edge points forward, from an earlier node to a later one.
Put first the nodes that no edge points to. Then remove their edges: every node that no edge points to anymore goes next. Repeat until every node is placed.
Cycle detection. O(V + E) time.
Given a directed graph, check if it has a cycle.
DFS follows one path at a time. If it reaches a node that is already on the current path, the path loops back, so there is a cycle. Keep two sets: path for the nodes on the current path, and visited for the finished nodes, so they are not walked again.
Shortest path. O(V + E) time.
Given a graph and a start node, find the fewest edges from the start to every node it can reach.
BFS reaches the nodes level by level, so the first time it reaches a node is by the fewest edges. Every new node is one edge further than the node it came from.
Other algorithms
The algorithms above are obviously not the full list. Others exist, but they are very rare in interviews, because they depend on knowing a specific trick or take too long to implement.
So again, I recommend practising problems rather than learning how each specific algorithm works. But if you still want to study them or want to come to them later, here is what could come up:
- Union-find (disjoint set union) keeps groups of connected nodes.
- Minimum spanning tree (Kruskal, Prim) finds the cheapest set of edges that connects every node.
- Dijkstra finds the cheapest path from one node to every other node when edge weights are non-negative.
- Bellman-Ford finds shortest paths when some edge weights are negative.
- Floyd-Warshall finds shortest paths between every pair of nodes.
- Strongly connected components (Tarjan, Kosaraju) finds groups of nodes in a directed graph where every node can reach every other one.
- Bridges and articulation points (Tarjan) finds edges and nodes whose removal splits the graph.
- Eulerian path (Hierholzer) finds a path that uses every edge exactly once.
- Maximum flow (Ford-Fulkerson, Edmonds-Karp) finds how much can flow from one node to another through edges with capacities.
- A* search is Dijkstra guided by an estimate of the remaining distance.