oneby7

Advanced Graphs Special edges and paths

489. Strongly Connected Components (Kosaraju)

Hard

You are given a directed graph with n vertices, numbered from 0 to n - 1. Each pair [u, v] in edges is an edge from vertex u to vertex v. An edge can be followed only in its own direction, from u to v.

A strongly connected component is a largest group of vertices in which every vertex can reach every other one by following edges. Every vertex belongs to exactly one component. A vertex with no path back to itself is a component on its own.

Return the number of strongly connected components in the graph.

Example 1

012345

Input: n = 6 edges = [[0, 1], [1, 2], [2, 0], [2, 3], [3, 4], [4, 3], [4, 5]]

Output: 3

Explanation: Vertices 0, 1 and 2 reach each other around the cycle 0 → 1 → 2 → 0. Vertices 3 and 4 have an edge each way. Nothing leads back from 3 to the cycle, or from 5 to anything, so the components are 0, 1, 2, then 3, 4, then 5 alone.

Example 2

0123

Input: n = 4, edges = [[0, 1], [1, 2], [0, 2], [3, 2]]

Output: 4

Explanation: No path returns to the vertex it started from. So no two vertices reach each other, and each vertex is a component on its own.

Example 3

012

Input: n = 3, edges = [[0, 0], [1, 2], [2, 1]]

Output: 2

Explanation: The edge [0,0] joins vertex 0 to nothing else, so 0 is a component alone. Vertices 1 and 2 have an edge each way and form the second component.

Check your understanding

Work out the answer for this input before you write any code.

n = 5, edges = [[0, 1], [1, 2], [2, 0], [3, 4]]

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ edges.length ≤ 105
  • edges[i].length == 2
  • 0 ≤ ui, vi < n
  • An edge can go from a vertex to itself, and the same edge can appear more than once.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.