Social feed~25 min2s · 256 MBtarget O(m log n) time, O(n + m) spacedijkstra · shortest-paths
A social feed shows a post to users one share at a time. A share goes from one user to another and takes a number of minutes to arrive. The post is first shown to one user, the origin, at minute 0.
A user sees the post at the earliest minute any chain of shares can bring it. Editors want to know when a quorum of users has seen it, counting the origin. The post may never reach enough users.
Write minutes_until_seen(n, shares, origin, quorum).
n users, numbered from 0 to n - 1.shares[i] is [from, to, minutes]: a one-way share that takes minutes minutes. Many shares may join the same pair.quorum users have seen the post, counting the origin. That is the quorum-th smallest minute.quorum users ever see it.Input: n = 6, shares = [[0,1,4],[0,2,1],[2,1,2],[1,3,5],[2,4,8],[4,5,1]], origin = 0, quorum = 4
Output: 8The minutes are: user 0 at 0, user 2 at 1, user 1 at 3, user 3 at 8, user 4 at 9 and user 5 at 10. User 1 is reached through user 2. The fourth user to see the post is user 3.
The solution takes users from a heap in order of minute, and stops when it has taken quorum users.
| Order | User | Minute first seen |
|---|---|---|
| 1 | 0 | 0 |
| 2 | 2 | 1 |
| 3 | 1 | 3 |
| 4 | 3 | 8 |
| 5 | 4 | 9 |
| 6 | 5 | 10 |
The fourth row has minute 8, so the answer is 8.
Input: n = 3, shares = [[0,1,2]], origin = 0, quorum = 3
Output: -1User 2 is never reached, so only two users see the post, and a quorum of 3 is never met.
Input: n = 5, shares = [[0,1,2],[1,2,2],[2,3,2],[3,4,2]], origin = 0, quorum = 1
Output: 0The origin counts, and it has seen the post at minute 0.
1 ≤ n ≤ 50,000, 0 ≤ origin < n and 1 ≤ quorum ≤ n0 ≤ shares.length ≤ 100,000, and each share is [from, to, minutes] with 0 ≤ from, to < n and 1 ≤ minutes ≤ 10,000Repeating a pass over all shares until nothing changes costs up to n × m steps. For 50,000 users and 100,000 shares that is 5 × 10^9. A heap handles each share once with a log factor, about 100,000 × 16 = 1.6 × 10^6 steps. The largest minute is 50,000 × 10,000 = 5 × 10^8, which fits in a 32-bit integer.