Engineering platform~45 min2s · 256 MBtarget O(n + m) time, O(n + m) spacetopological-sort · dfs
A platform installs plugins, and some plugins require others. Most requirements form a clean chain, but a few plugins require each other in a circle: plugin A needs B, and B needs A. Such plugins cannot be installed one at a time, so the installer treats every circle as one group and installs the group together.
The installer works in rounds. In one round it installs, in parallel, every group whose requirements are already installed. Operations wants to know how many rounds a full install needs.
Write install_rounds(n, requires).
0 to n - 1. Each pair [a, b] in requires means that plugin a requires plugin b. Pairs may repeat, and a plugin may require itself.Input: n = 7, requires = [[0, 1], [1, 0], [1, 2], [2, 3], [3, 4], [4, 2], [5, 4], [5, 6]]
Output: 2Plugins 0 and 1 require each other, so they form one group. Plugins 2, 3 and 4 form a circle: 2 needs 3, 3 needs 4 and 4 needs 2. Plugin 5 needs 4 and 6.
| Group | Plugins | Needs (outside the group) | Round |
|---|---|---|---|
| A | 2, 3, 4 | none | 1 |
| B | 6 | none | 1 |
| C | 0, 1 | group A (through plugin 1 needing 2) | 2 |
| D | 5 | group A and group B | 2 |
The output is 2.
Input: n = 3, requires = []
Output: 1With no requirements, all three plugins install in the first round.
Input: n = 3, requires = [[0, 1], [1, 2], [2, 0]]
Output: 1The three plugins form one circle, so they are one group, installed in one round.
1 ≤ n ≤ 100,000 (plugins)0 ≤ requires.length ≤ 100,000 (requirements); each pair has 2 numbers from 0 to n - 1Finding the groups by testing every pair of plugins for mutual reach costs about n² × (n + m) steps, which is far too many. The groups are the strongly connected components of the requirement graph, and two depth-first passes find them in n + m steps. A chain of 100,000 plugins is also 100,000 levels deep, so the passes need an explicit stack, not recursion.