Kosaraju's algorithm

Graphs Additional Algorithms Hard
  • Fun Fact: The concept of finding strongly connected components in a directed graph has real-world applications in many fields like social media, search engines, and recommendation systems
  • Did you know, in social media, it is used to identify tightly-knit community structures? For example, one where everyone is friends with everyone else or everyone follows everyone else
  • It also helps in analyzing web pages, where each page is a vertex and hyperlinks are directed edges
  • By finding the strongly connected components, search engines can identify groups of pages that are highly interlinked, improving search results
  • So, next time when you see groups in your social media or clustered search results remember, it's derived from this graph problem!

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