Social feed~40 min2s · 256 MBtarget O(n + m) time, O(n + m) spacebfs
A reading app links related topics. Every link points from a topic to a related one. Two readers play a game: a token sits on a topic, and the readers take turns to move it along one link.
A reader who is on a topic with no link out cannot move, and loses. If play can go on for ever, the game is a draw. Your team lead asks: "For each starting topic, who wins?" There can be 50,000 topics and 100,000 links.
Write game_outcomes(n, links).
n is the number of topics, numbered 0 to n - 1.links[i] = [a, b] is a link from topic a to topic b. A link can point to its own topic, and the same link can appear twice.n numbers. Entry v is 1 when the first reader wins from topic v, -1 when the first reader loses, and 0 for a draw.Input: n = 6, links = [[0, 1], [1, 2], [1, 3], [3, 4], [4, 3], [5, 2]]
Output: [-1, 1, -1, 0, 0, 1]Work backwards from the topic with no link out. Each row shows one decided topic and what it tells the topics that link into it:
| Step | Decided topic | What it tells the topics that link into it |
|---|---|---|
| 1 | 2 (loses: no link out) | Topics 1 and 5 can move into a loss, so they win |
| 2 | 1 (wins) | Topic 0 has one link out, and it leads to a win, so topic 0 loses |
| 3 | 5 (wins) | No topic links into topic 5 |
| 4 | 0 (loses) | No topic links into topic 0 |
Topics 3 and 4 link to each other, and neither has a move that leads to a loss. Play between them never ends, so both are draws.
Input: n = 1, links = []
Output: [-1]The only topic has no link out, so the first reader cannot move.
Input: n = 2, links = [[0, 1], [1, 0]]
Output: [0, 0]The token goes round for ever, and neither reader can do better.
1 ≤ n ≤ 50,0000 ≤ len(links) ≤ 100,0000 ≤ a, b < n for every link [a, b]Playing out the game from every topic could take a very long time, because play can loop. Repeating sweeps until nothing changes can need one sweep for each topic on a long chain. That is about 5 billion steps for 50,000 topics and 100,000 links. The outcomes must be found with each link looked at a constant number of times.