Bank app~20 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-1136topological-sort
A bank closes its month by closing ledgers, numbered from 0. A ledger can close only after every ledger that feeds it has closed.
Any number of ledgers may close on the same day. Once a ledger is ready, it closes that day. You want the fewest days needed to close every ledger.
Write fewest_close_days(n, feeds).
n ledgers, numbered from 0 to n - 1.feeds[i] is [a, b]: ledger a feeds ledger b, so a must close on an earlier day than b. A line may repeat.Input: n = 6, feeds = [[0,2],[1,2],[2,3],[2,4],[3,5],[4,5]]
Output: 4Ledgers 0 and 1 wait for nothing, so they close on day 1. Ledger 2 waits for both, and ledger 5 waits for 3 and 4.
Each day closes every ledger whose feeders are all closed.
| Day | Ledgers closed | Ledgers still waiting |
|---|---|---|
| 1 | 0, 1 | 2, 3, 4, 5 |
| 2 | 2 | 3, 4, 5 |
| 3 | 3, 4 | 5 |
| 4 | 5 | none |
The answer is 4, the number of days.
Input: n = 3, feeds = [[0,1],[1,2],[2,1]]
Output: -1Ledger 0 closes on day 1. Ledgers 1 and 2 each wait for the other, so neither can close.
Input: n = 4, feeds = []
Output: 1With no feeds, every ledger is ready on day 1, and all four close on that day.
1 ≤ n ≤ 50,0000 ≤ feeds.length ≤ 100,000, and each line is [a, b] with 0 ≤ a, b < nSimulating each day by scanning every ledger and every feed line costs about n × m. For 50,000 ledgers and 100,000 lines that is up to 5 × 10^9 steps. Closing each ledger once and releasing the ledgers it feeds costs n + m, about 150,000 steps.