Skip to content

ORIGINAL CODING QUESTION

Modules you can actually finish

A course catalogue has n modules and m prerequisite pairs (a,b) meaning module a must be finished before module b can begin. A module becomes finishable once every one of its prerequisites is finished. Return how many modules can eventually be finished. Modules inside a circular chain, or depending on one, never become finishable; a pair (a,a) blocks module a.

Open practice workspace

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

Input and output

n m, then m prerequisite pairs (a,b), zero-based.

Constraints

1 ≤ n ≤ 30; 0 ≤ m ≤ 100; module IDs in [0,n). Repeated pairs are allowed.

Example 1

Input

4 3 0 1 1 2 2 3

Output

4

The chain can be finished in order.

Example 2

Input

4 4 0 1 1 2 2 1 0 3

Output

2

Modules 1 and 2 wait on each other; only 0 and 3 can be finished.

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

A module with no unfinished prerequisites can be finished right away.

Hint 2

Finishing a module reduces the waiting count of the modules that depend on it.

Hint 3

Process modules whose waiting count reaches zero (Kahn's algorithm) and count how many you process.

Practice this question

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

Open practice workspaceBrowse the question library →