Kosaraju's algorithm

Graphs Additional Algorithms Hard

Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges. An edge is represented [ai,bi] denoting a directed edge from vertex ai to bi. Find the number of strongly connected components in the graph.

Examples:

Input: V=5, E=[[0,2], [1,0], [2,1], [0,3], [3,4]]



Output: 3

Explanation: Three strongly connected components are marked below:


Input: V=8, E=[[0,1], [1,2], [2,0], [2,3], [3,4], [4,5], [4,7], [5,6], [6,4], [6,7]]


Output: 4

Explanation: Four strongly connected components are marked below:


Input: V=3, E=[[0,1], [1,2]]

Constraints

1 ≤ V ≤ 5000

0 ≤ E ≤ (V*(V-1))

0 ≤ ai, bi ≤ V-1

Hints

  • Perform DFS in normal order, storing nodes in a stack based on their finishing time (Topological Sort).
  • Reverse the graph (transpose the edges) and process nodes in stack order, counting SCCs using another DFS.

Company Tags

Lyft Goldman Sachs Airbnb Bain & Company Dropbox Johnson & Johnson HCL Technologies Intel Byju's JPMorgan Chase Zomato Freshworks Ernst & Young Epic Games MongoDB Visa Nutanix Pinterest AMD NVIDIA Philips Healthcare Qualcomm Rakuten Optum DoorDash Google Microsoft Amazon Meta Apple Netflix Adobe