Engineering platform~30 min2s · 256 MBtarget O(n + r) time, O(n + r) spaceclassic twin: lc-207cycle-detection · topological-sort
A platform has n feature flags, numbered from 0. A flag can be switched on only when its requirements are met. A flag with no requirement can be switched on at any time.
A requirement is a short list of flags, and it is met when at least one flag on the list is already on. A flag may have several requirements, and all of them must be met. The team switches flags on one at a time and wants to know how many can ever be on.
Write count_enabled_flags(n, needs).
needs[i] is [f, a1, a2, ...]: one requirement of flag f, met when at least one of a1, a2, ... is on. A row has one to five options.Input: n = 6, needs = [[2,0,1],[3,2],[4,2,3],[4,5],[5,4]]
Output: 4Flags 0 and 1 have no row, so they are ready. A queue switches on a ready flag and then meets the rows that name it.
| Step | Flag switched on | Rows met | Newly ready |
|---|---|---|---|
| 1 | 0 | row [2,0,1] |
flag 2 |
| 2 | 1 | none: that row is already met | none |
| 3 | 2 | rows [3,2] and [4,2,3] |
flag 3 |
| 4 | 3 | none: row [4,2,3] is already met |
none |
Flag 4 also needs row [4,5], and flag 5 needs row [5,4]. Flags 4 and 5 wait for each other, so neither can start. Four flags can be on.
Input: n = 3, needs = [[1,1],[2,0,1]]
Output: 2Flag 1 needs itself and never starts. Flag 2 needs one of flags 0 and 1, and flag 0 is on, so flag 2 can start.
Input: n = 1, needs = []
Output: 1A flag with no requirement can be switched on.
1 ≤ n ≤ 100,0000 ≤ needs.length ≤ 100,000, each row has 2 to 6 numbers from 0 to n - 1Sweeping over all flags again and again, and rescanning all rows for each flag, can need a sweep for every flag on a long chain. With 100,000 flags and 100,000 rows that is about 10^15 steps. A queue that handles each row once when its first option turns on costs O(n + r).