Music streaming app~30 min2s · 256 MBtarget O(n + m) time, O(n + m) spacedp
You work on a streaming app. The app has n pages, numbered 0 to n - 1. A viewer starts on page 0 and follows one-way links until the last page, n - 1. The links never lead back to an earlier page of the same journey, so no journey can loop.
Some pages show a promotion. The marketing team wants to know how many different journeys pass at least one promotion page.
Your team lead asks: "How many journeys from the first page to the last page pass a promotion page?" The app can have 100,000 pages, and the count can be very large.
Write count_promo_journeys(n, links, promo).
links[k] = [a, b] is a one-way link from page a to page b. The links form no cycle. Links can repeat, and every copy counts as a different link.0 to page n - 1. Each link starts at the page where the previous one ended. For n = 1 the journey is the single page 0, with no links.promo lists the promotion pages, each at most once.1,000,000,007.Input: n = 6, links = [[0, 3], [0, 2], [3, 1], [2, 1], [3, 4], [1, 5], [4, 5]], promo = [2]
Output: 1There are 3 journeys from page 0 to page 5. Which of them pass the promotion page 2:
| Journey | Passes page 2? |
|---|---|
| 0 → 2 → 1 → 5 | yes |
| 0 → 3 → 1 → 5 | no |
| 0 → 3 → 4 → 5 | no |
Exactly one journey passes a promotion page.
Input: n = 3, links = [[0, 1], [1, 2]], promo = []
Output: 0There is no promotion page, so no journey passes one.
Input: n = 1, links = [], promo = [0]
Output: 1The only journey is the first page, which is the last page, and it is a promotion page.
1 ≤ n ≤ 100,0000 ≤ len(links) ≤ 200,0000 ≤ links[k][0], links[k][1] < n, and the links contain no cycle0 ≤ len(promo) ≤ n, with distinct page numbers1,000,000,007.The number of journeys can be exponential. A chain of 70 pairs of pages, where every page links to both pages of the next pair, has 2 to the power 70 = 1,180,591,620,717,411,303,424 journeys. Following them one by one is impossible. The links form no cycle, so the journeys into a page can be added up page by page.