GeeksforGeeks Medium

Strongly Connected Components (Kosaraju)

Strongly Connected Components (Kosaraju) is a GFG problem (Medium). You get a directed graph with V vertices numbered 0 to V − 1 and a list edges, where [u, v] is an edge from u to v. Return the number of strongly connected components.

  • A strongly connected component (SCC) is a largest group of vertices in which every vertex can reach every other one by following edges forward.
  • Every vertex is in exactly one component. A vertex that lies on no cycle is a component on its own.

Both V and E go up to 10⁶, so the count must take O(V + E) time, and a recursive DFS would run out of stack on a long chain of vertices.

Constraints
  • 1 <= V <= 10⁶
  • 0 <= E <= 10⁶
  • 0 <= edges[i][0], edges[i][1] < V
graphdfsscckosaraju
Open on GeeksforGeeks ↗
02

Intuition

A DFS started inside a component that has no edge leaving it reaches exactly that component. Kosaraju's algorithm for SCCs finds such components one by one:

  • Pass 1, finish order: run DFS on the graph and note when each vertex finishes. The vertex that finishes last sits in a component that no other component points into.
  • Pass 2, reversed edges: reversing every edge keeps each component the same but leaves that component with no way out, so a DFS from it marks exactly one component. The next unmarked vertex in finish order repeats the trick: its reversed edges can only leave into components already marked.
How to spot this pattern

"Groups where everyone can reach everyone" in a directed graph is a strongly connected component problem. Two-way reachability is the tell: in an undirected graph plain connected components would do, but one-way edges need the two passes.

03

Approach

Try it first

Before reading on, take a graph with two cycles joined by one edge and ask where a DFS started in each cycle would end up. Then think about which cycle you would want to start from, and whether reversing the edges helps. Aim for O(V + E).

1

Build the graph and its reverse

For each edge [u, v], add v to adj[u] and u to radj[v]. Building both lists in one loop means the reversed graph is ready for the second pass without another scan of the edges.

2

Pass 1: record the finish order

From every unvisited vertex, run DFS on adj with an explicit stack and a pointer it[v] to the next neighbour to try. When v has no neighbours left, pop it and append it to order. A vertex is recorded only after everything reachable from it, which is what makes the last vertex in order a safe place to start.

3

Pass 2: walk the order from the end

Go through order from the last vertex to the first. A vertex that is still unmarked belongs to a component nobody has found yet, so add 1 to the count and start a search from it.

4

Mark everything reachable on reversed edges

Use a plain stack on radj and mark every vertex you reach. The search stays inside one component: any reversed edge that leaves it points into a component that was started earlier in this pass, and those vertices are already marked.

5

Return the count

Each vertex is marked once in pass 2, so after the loop the count equals the number of strongly connected components. To list the components instead, collect the vertices each search marks.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def countSCC(self, V, edges):
▶3 adj = [[] for _ in range(V)]
▶4 radj = [[] for _ in range(V)]
▶5 for u, v in edges:
▶6 adj[u].append(v)
▶7 radj[v].append(u)
▶8 
▶9 seen = [False] * V
▶10 it = [0] * V
▶11 order = []
▶12 for s in range(V):
▶13 if seen[s]:
▶14 continue
▶15 seen[s] = True
▶16 stack = [s]
▶17 while stack:
▶18 v = stack[-1]
▶19 if it[v] < len(adj[v]):
▶20 u = adj[v][it[v]]
▶21 it[v] += 1
▶22 if not seen[u]:
▶23 seen[u] = True
▶24 stack.append(u)
▶25 else:
▶26 stack.pop()
▶27 order.append(v)
▶28 
▶29 seen = [False] * V
▶30 count = 0
▶31 for s in reversed(order):
▶32 if seen[s]:
▶33 continue
▶34 count += 1
▶35 seen[s] = True
▶36 stack = [s]
▶37 while stack:
▶38 v = stack.pop()
▶39 for u in radj[v]:
▶40 if not seen[u]:
▶41 seen[u] = True
▶42 stack.append(u)
▶43 return count
pass 1 · edges as given0123finish orderfirstlastsccsfound in pass 2pass 1: start the DFS at 0
stack[0]
order[]
Pass 1 walks the graph as given and records each vertex when it finishes, that is, once every vertex it can reach has been explored. Start at vertex 0.
pass 1 · edges as given0123finish orderfirstlastsccsfound in pass 20 → 1: new vertex, go deeper
edge0 → 1
stack[0, 1]
Vertex 1 has not been seen, so the DFS moves on to it. 0 cannot finish until 1 and everything after it is done.
pass 1 · edges as given0123finish orderfirstlastsccsfound in pass 21 → 0: already visited, skip
edge1 → 0
stack[0, 1]
Vertex 0 was already visited and is still on the stack, so this edge adds nothing new. 1 goes on to its next edge.
pass 1 · edges as given0123finish orderfirstlastsccsfound in pass 21 → 2: new vertex, go deeper
edge1 → 2
stack[0, 1, 2]
Vertex 2 has not been seen, so the DFS moves on to it. 1 cannot finish until 2 and everything after it is done.
pass 1 · edges as given0123finish orderfirstlastsccsfound in pass 22 → 3: new vertex, go deeper
edge2 → 3
stack[0, 1, 2, 3]
Vertex 3 has not been seen, so the DFS moves on to it. 2 cannot finish until 3 and everything after it is done.
pass 1 · edges as given0123finish orderfirstlastsccsfound in pass 23 → 2: already visited, skip
edge3 → 2
stack[0, 1, 2, 3]
Vertex 2 was already visited and is still on the stack, so this edge adds nothing new. 3 goes on to its next edge.
pass 1 · edges as given0123finish order3firstlastsccsfound in pass 23 has no edges left → finishes 1st
order[3]
Every edge out of 3 has been tried, so 3 finishes and goes to the top of the finish order. Everything 3 can reach finished before it, which is why the order matters.
pass 1 · edges as given0123finish order3first2lastsccsfound in pass 22 has no edges left → finishes 2nd
order[3, 2]
Every edge out of 2 has been tried, so 2 finishes and goes to the top of the finish order. Everything 2 can reach finished before it, which is why the order matters.
pass 1 · edges as given0123finish order3first21lastsccsfound in pass 21 has no edges left → finishes 3rd
order[3, 2, 1]
Every edge out of 1 has been tried, so 1 finishes and goes to the top of the finish order. Everything 1 can reach finished before it, which is why the order matters.
pass 1 · edges as given0123finish order3first210lastsccsfound in pass 20 has no edges left → finishes 4th
order[3, 2, 1, 0]
Every edge out of 0 has been tried, so 0 finishes and goes to the top of the finish order. Everything 0 can reach finished before it, which is why the order matters.
pass 2 · edges reversed0123finish order3first210lastsccsnone yetflip every edge, read the order from the top
order[3, 2, 1, 0]
seenall cleared
Every arrow now points the other way. Each component keeps the same vertices, since a path both ways stays a path both ways, but the edges between components are reversed. The last finisher, 0, is read first.
pass 2 · edges reversed0A123finish order3first210last▶sccsA: 00 is unmarked → new component A
s0
count1
Vertex 0 is not in any component yet, so it starts component A and the count becomes 1. It finished last, so no other component points into it; with the edges flipped, nothing leads out of its component.
pass 2 · edges reversed0A1A23finish order3first210last▶sccsA: 0 10 → 1 flipped: 1 joins A
edge0 → 1was 1 → 0
A[0, 1]
Following the flipped edge reaches 1, which is unmarked. In the original graph 1 leads to 0, and this search cannot leave its component, so 1 joins component A.
pass 2 · edges reversed0A1A23finish order3first210last▶sccsA: 0 11 → 0 flipped: 0 is already in A
edge1 → 0was 0 → 1
A[0, 1]
Vertex 0 is already in A, so there is nothing to add.
pass 2 · edges reversed0A1A23finish order3first21▶0lastsccsA: 0 11 is already in A → skip
s1in component A
Vertex 1 was marked while building component A, so it does not start a new one.
pass 2 · edges reversed0A1A2B3finish order3first2▶10lastsccsA: 0 1B: 22 is unmarked → new component B
s2
count2
Vertex 2 is not in any component yet, so it starts component B and the count becomes 2. Any flipped edge leaving its component can only lead into a component already marked.
pass 2 · edges reversed0A1A2B3finish order3first2▶10lastsccsA: 0 1B: 22 → 1 flipped: 1 is in A, stay out
edge2 → 1was 1 → 2
B[2]
This flipped edge leads into component A, which is already finished. The mark stops the search here, so B does not swallow vertices that only reach it one way.
pass 2 · edges reversed0A1A2B3Bfinish order3first2▶10lastsccsA: 0 1B: 2 32 → 3 flipped: 3 joins B
edge2 → 3was 3 → 2
B[2, 3]
Following the flipped edge reaches 3, which is unmarked. In the original graph 3 leads to 2, and this search cannot leave its component, so 3 joins component B.
pass 2 · edges reversed0A1A2B3Bfinish order3first2▶10lastsccsA: 0 1B: 2 33 → 2 flipped: 2 is already in B
edge3 → 2was 2 → 3
B[2, 3]
Vertex 2 is already in B, so there is nothing to add.
pass 2 · edges reversed0A1A2B3Bfinish order3first▶210lastsccsA: 0 1B: 2 33 is already in B → skip
s3in component B
Vertex 3 was marked while building component B, so it does not start a new one.
pass 2 · edges reversed0A1A2B3Bfinish order3first210lastsccsA: 0 1B: 2 3answer: 2 components
count2
Every vertex is in exactly one component, so the count is 2. Each vertex and each edge was handled once per pass, which is O(V + E).
05

Common pitfalls

Recursive DFS on a long chain

✗ Wrong
def dfs(v):
    seen[v] = True
    for u in adj[v]:
        if not seen[u]:
            dfs(u)
    order.append(v)
✓ Right
stack = [s]
while stack:
    v = stack[-1]
    if it[v] < len(adj[v]):
        ...
    else:
        stack.pop()
        order.append(v)

With edges 0 → 1 → 2 → … → 10⁵ the recursion goes 10⁵ calls deep. Python stops at about 1,000 with RecursionError, and C++ and Java can overflow their call stacks well before 10⁶. The explicit stack with a next-neighbour pointer gives the same finish order with no depth limit.

Recording a vertex when it is first visited

✗ Wrong
seen[u] = True
order.append(u)
stack.append(u)
✓ Right
else:
    stack.pop()
    order.append(v)

The proof needs finish order. With V = 2 and edges = [[0, 1]], visit order is [0, 1], so pass 2 starts from 1, follows the reversed edge to 0 and counts one component. The answer is 2: 0 and 1 cannot reach each other both ways.

Walking the finish order from the front

✗ Wrong
for s in order:
✓ Right
for s in reversed(order):

The first vertex to finish sits in a component that other components point into, so on reversed edges it can escape. With edges = [[0, 1]] the order is [1, 0]; starting at 1 reaches 0 and the code returns 1 instead of 2.

Searching the original edges in pass 2

✗ Wrong
for u in adj[v]:
✓ Right
for u in radj[v]:

Forward edges lead out of the component the search starts in. With edges = [[0, 1]] pass 2 starts at 0, follows 0 → 1 and merges two components into one.

06

Edge cases

No edges, e.g. V = 3, edges = []

Every vertex finishes alone in pass 1 and starts its own search in pass 2, so the count is V, here 3.

Vertices that 0 cannot reach

Pass 1 loops over every vertex as a possible start, so a vertex with no path from 0 still gets a finish time and is counted.

A self-loop such as [2, 2]

Vertex 2 is already marked when its own edge is checked, so the loop changes nothing and 2 is still one component.

07

Complexity

Time
O(V + E)
Space
O(V + E)
Each pass visits every vertex once and looks at every edge once. The space holds the two adjacency lists, the finish order and the explicit stack.
08

Strongly Connected Components (Kosaraju) FAQ

Why does the vertex that finishes last lie in a component nothing points into?

Take an edge from component C to component D. If the DFS enters C first, it reaches all of D before it can leave C, so C's last finish is later. If it enters D first, it cannot reach C (or C and D would be one component), so all of D finishes before C even starts. Either way C finishes after D, so the overall last finisher has no component pointing into it.

Kosaraju or Tarjan: which should I use?

Both run in O(V + E). Tarjan's algorithm needs one DFS and no reversed graph, using a low-link value per vertex to spot where a component ends. Kosaraju's two passes are easier to explain and to get right in an interview, and the reversed graph costs only one extra list per vertex.

Does pass 2 have to be a DFS?

No. Pass 2 only needs to mark everything reachable on the reversed edges, so a BFS or any stack order works. Only pass 1 must be a true DFS, because it depends on finish times.