Topological Sorting and Strongly Connected Components

In the world of competitive programming, a strong foundation in various algorithms and data structures is crucial. Two such concepts that often come up in problem-solving are topological sorting and strongly connected components. Understanding these concepts and being able to apply them can lead to more efficient solutions and better performance.

Topological Sorting

Topological sorting is an algorithmic approach used to order the vertices of a directed graph in such a way that for every directed edge (u, v), vertex u comes before vertex v in the ordering. The resulting ordering is known as a topological order.

The main idea behind topological sorting is to identify a vertex that has no incoming edges (i.e., no edges with it as the destination vertex). This vertex is then removed from the graph, and the process is repeated recursively until all vertices have been visited. The order in which vertices are removed gives a valid topological order.

Topological sorting can be used to solve various types of problems, such as determining the order of tasks or dependencies in a project. It can also help detect cycles in a directed graph. If a graph has a valid topological order, it is acyclic. Otherwise, it contains at least one cycle.

Strongly Connected Components

A strongly connected component (SCC) in a directed graph is a subset of vertices where every vertex can reach every other vertex in the same subset.

There are different algorithms to find strongly connected components, but one of the most popular ones is Tarjan's Algorithm. Tarjan's Algorithm is based on depth-first search and uses a stack to keep track of the visited vertices and their low-link values.

The algorithm works by performing a depth-first search on the graph, assigning a unique index to each vertex as it is visited. It also maintains a stack of visited vertices. For each visited vertex, it assigns a low-link value, which represents the earliest discovered vertex reachable from that vertex.

By repeatedly visiting vertices and updating the low-link values, the algorithm identifies strongly connected components. Once all vertices have been visited, the algorithm outputs the SCCs.

Strongly connected components are useful in various applications, such as finding clusters in social networks, detecting strongly connected areas in maps, or identifying interconnected systems in a computer network.


Topological sorting and strongly connected components are powerful techniques in competitive programming. They offer elegant solutions to problems involving directed graphs and dependencies. By understanding and implementing these concepts efficiently, one can improve their problem-solving skills and tackle more complex challenges.

noob to master © copyleft