Skip to content

ORIGINAL CODING QUESTION

Mutual reachability groups

Count strongly connected components of a directed graph. Every pair of vertices within one group can reach each other.

Open practice workspace

Original exercise · hard. Editorial role relevance does not imply a company has asked this question.

Input and output

n m, then m vertex pairs (u,v). Vertices are zero-based.

Constraints

1 ≤ n ≤ 30; 0 ≤ m ≤ 100; vertex IDs in [0,n).

Example 1

Input

3 3 0 1 1 0 1 2

Output

2

Vertices 0 and 1 share a group; 2 is separate.

Example 2

Input

3 3 0 1 1 2 2 0

Output

1

All three vertices are mutually reachable.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

One-way reachability does not imply shared membership.

Hint 2

A finishing-order traversal and reversed edges form a standard approach.

Hint 3

Alternatively reason about mutual reachability on small graphs.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →