Social feed~30 min2s · 256 MBtarget O(n + m) time, O(n + m) spacebfs
A social app lets a user ask to be introduced to another user through mutual friends. An introduction passes along a chain of friends, one hop at a time. Users with a private profile accept a request but do not pass it on.
The app wants to know how short the shortest chain is, and how many different chains of that length exist. More chains mean a better chance that a request gets through.
Write count_shortest_chains(n, edges_a, edges_b, private, start, target).
0 to n - 1. Friendship i joins edges_a[i] and edges_b[i], and works in both directions. start and target are different.private[p] is 1 when person p has a private profile. A chain may end at a private person, and it may start at one, but it may not pass through one.start to target, and the number of different chains with that many hops, modulo 1,000,000,007.[-1, 0].Input: n = 7, edges_a = [0, 0, 1, 2, 3, 2, 5, 4], edges_b = [1, 2, 3, 3, 4, 5, 4, 6], private = [0, 0, 0, 0, 0, 1, 0], start = 0, target = 4
Output: [3, 2]The trace shows people in the order a breadth-first search takes them from the queue.
| Order | Person | Hops from 0 | Shortest chains | What happens |
|---|---|---|---|---|
| 1 | 0 | 0 | 1 | passes its chains to its friends |
| 2 | 1 | 1 | 1 | passes its chains to its friends |
| 3 | 2 | 1 | 1 | passes its chains to its friends |
| 4 | 3 | 2 | 2 | passes its chains to its friends |
| 5 | 5 | 2 | 1 | private: passes nothing on |
| 6 | 4 | 3 | 2 | passes its chains to its friends |
| 7 | 6 | 4 | 2 | passes its chains to its friends |
Chains 0, 1, 3, 4 and 0, 2, 3, 4 both have 3 hops. The chain 0, 2, 5, 4 also has 3 hops, but person 5 is private, so it does not count. The output is 3 hops and 2 chains.
Input: n = 4, edges_a = [0, 2], edges_b = [1, 3], private = [0, 0, 0, 0], start = 0, target = 3
Output: [-1, 0]Persons 0 and 1 know each other, and so do 2 and 3, but nobody connects the two pairs. The output is minus one hops and 0 chains.
Input: n = 3, edges_a = [0, 0, 1], edges_b = [1, 2, 2], private = [0, 0, 0], start = 0, target = 2
Output: [1, 1]Person 2 is a direct friend of person 0, so the shortest chain has 1 hop. The chain through person 1 has 2 hops, so it does not count. The output is 1 hop and 1 chain.
2 ≤ n ≤ 100,000 (people); 1 ≤ edges_a.length ≤ 100,000; edges_b has the same length0 ≤ edges_a[i], edges_b[i] < nprivate.length = n, and each value is 0 or 10 ≤ start, target < n, start ≠ targetListing every chain between two people can take exponential time, because the number of chains of the same length can double at every step. Breadth-first search finds the hops in n + m steps. It can also add up the number of chains as it goes, so it never lists them. That count can be huge, which is why the answer asks for it modulo 1,000,000,007.