Ctrl K

Spread the News to Everyone

Hard
A company has people people, numbered 0 to people - 1. Everyone listed in informed already knows an important piece of news. There are also one-way channels: through channel i, person tells_from[i] passes on everything they know to person tells_to[i] (but not the other way round). The news travels along channels for any number of steps. You may add new one-way channels between any two people. Return the smallest number of new channels needed so that the news reaches everyone.
Example 1
people=5, informed=[0], tells_from=[0, 2, 3], tells_to=[1, 3, 2] → 2

The news goes from 0 to 1. People 2 and 3 pass it to each other, so a single link from someone who already knows into 2 or 3 covers both. Person 4 is not connected to anyone and needs one more link. That is 2.

Example 2
people=4, informed=[3], tells_from=[3, 1, 2], tells_to=[1, 2, 0] → 0

The chain 3 → 1 → 2 → 0 already reaches everyone, so no new links are needed.

Example 3
people=3, informed=[1], tells_from=[], tells_to=[] → 2
Constraints
  • 2 ≤ people ≤ 10⁵
  • 1 ≤ len(informed) ≤ people, 0 ≤ informed[i] < people
  • 0 ≤ len(tells_from) = len(tells_to) ≤ 2·10⁵
  • 0 ≤ tells_from[i], tells_to[i] < people, tells_from[i] ≠ tells_to[i]
  • All channels are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLetter Order From a Dictionary HardLongest Uphill Walk HardWhich Machine to Cure HardWhich Machine to Unplug HardUphill-Only Walks Hard
loading Python…
Input
people=5, informed=[0], tells_from=[0, 2, 3], tells_to=[1, 3, 2]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 51 tests on the server, hidden ones included.