Chat app~30 min2s · 256 MBtarget O(n + m) time, O(n + m) spacebfs
You work on a chat service that relays messages between servers. The servers are numbered 0 to n - 1, and each link joins two servers and works in both directions.
A message goes from a source server to a target server. To keep the traffic predictable, the service always uses a route with the fewest hops. When routes tie on hops, it uses the one that is smallest when you compare the server numbers in order, like words in a dictionary.
Your team lead asks: "Which route does a message take?" The service can have 100,000 servers.
Write smallest_route(n, links, source, target).
links[k] = [a, b] is a two-way link between servers a and b. Links can repeat, and a can equal b.source to target, where each neighbouring pair is joined by a link.source.[source] when source = target, and an empty list when target cannot be reached.Input: n = 6, links = [[0, 1], [0, 2], [1, 3], [2, 3], [3, 4], [2, 5], [5, 4]], source = 0, target = 4
Output: [0, 1, 3, 4]First count the hops from every server to the target 4:
| Server | Hops to the target |
|---|---|
| 0 | 3 |
| 1 | 2 |
| 2 | 2 |
| 3 | 1 |
| 4 | 0 |
| 5 | 1 |
Three routes have 3 hops: [0, 1, 3, 4], [0, 2, 3, 4] and [0, 2, 5, 4]. Walking from server 0, each step picks the smallest neighbour that is one hop closer:
| At server | Hops left | Neighbours one hop closer | Next server |
|---|---|---|---|
| 0 | 3 | 1, 2 | 1 |
| 1 | 2 | 3 | 3 |
| 3 | 1 | 4 | 4 |
The route is [0, 1, 3, 4].
Input: n = 4, links = [[0, 1], [2, 3]], source = 0, target = 3
Output: []Servers 0 and 1 are not linked to servers 2 and 3.
Input: n = 3, links = [[0, 1]], source = 2, target = 2
Output: [2]A message that is already at its target takes the route with the source alone.
1 ≤ n ≤ 100,0000 ≤ len(links) ≤ 200,0000 ≤ links[k][0], links[k][1], source, target < nListing every route from the source to the target takes exponential time in the worst case, because a network can have a huge number of equally short routes. Breadth-first search finds the hop counts in one pass over the servers and the links. The route is then built one step at a time.