DSA interview question
A social platform's "follows" graph is directed. A strongly connected component (SCC) is a maximal group of users where everyone can reach everyone else by following links, like a tightly knit community. Find all SCCs. Kosaraju's algorithm uses two DFS passes. The first records vertices by finish time. The second runs on the reversed graph, starting from vertices in decreasing finish time, and each DFS tree of that pass is exactly one SCC.
Example: 5 vertices, edges 1→0, 0→2, 2→1, 0→3, 3→4 → 3 SCCs: {0, 1, 2}, {3}, {4}.
vector<vector<int>> kosaraju(int V, const vector<pair<int, int>>& edges); // each SCC sorted; list sorted
Input (V, edges) | Output (count, SCCs) | Explanation |
|---|---|---|
(5, [[1,0],[0,2],[2,1],[0,3],[3,4]]) | 3 [[0, 1, 2], [3], [4]] | |
(6, [[0,1],[1,0],[2,3],[3,2],[1,2],[4,5]]) | 4 [[0, 1], [2, 3], [4], [5]] | 1→2 doesn't merge the pairs |
(3, [[0,1],[1,2],[2,0]]) | 1 [[0, 1, 2]] | One cycle |
(4, [[0,1],[1,2],[2,3]]) | 4 [[0], [1], [2], [3]] | A chain: no mutual reachability |
(1, []) | 1 [[0]] |
(Confirm: edges are directed; a single vertex is its own SCC; the output order is free, and it's sorted here.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in