KatInterview

Strongest Signal Route in a Lossy Link Network

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsgraphdijkstraheap

Last updated

Find the route between two nodes in an undirected graph that maximizes the product of per-link delivery probabilities, using a Dijkstra-style search with a max-priority queue.

Strongest Signal Route

A data center consists of n machines numbered 0 to n - 1. Machines are joined by bidirectional links. Each link is described by a triple [a, b, p]: it joins machines a and b, and a message sent across it arrives successfully with probability p, where 0.0 <= p <= 1.0.

The delivery probability of a route is the product of the probabilities of all links used on that route. A route that uses no links (that is, when the source and destination are the same machine) has delivery probability 1.0.

Write a function that returns the highest delivery probability achievable by any route from source to target. If the target cannot be reached from the source, return 0.0.

The input may contain parallel links (several links between the same pair of machines), self-loops, cycles, links with probability 0, and machines in separate disconnected parts of the network. Your answer must handle all of these correctly.

Parameters

  • n: the number of machines.
  • links: a list of [a, b, p] triples as described above.
  • source: the starting machine.
  • target: the destination machine.

Return value

A float: the maximum delivery probability over all routes from source to target, or 0.0 if no route gives a positive probability or none exists. An answer within 1e-5 of the true value is accepted.

Constraints

  • 1 <= n <= 10^5
  • 0 <= len(links) <= 2 * 10^5
  • Each link is [a, b, p] with 0 <= a, b < n and 0.0 <= p <= 1.0
  • 0 <= source, target < n
  • Parallel links and self-loops may appear.
  • Answers within 1e-5 of the exact value are accepted.

Examples

Example 1

Input: strongest_route(3, [[0, 1, 0.5], [1, 2, 0.5], [0, 2, 0.2]], 0, 2)

Output: 0.25

Example 2

Input: strongest_route(4, [[0, 1, 0.8], [1, 2, 0.5], [2, 3, 0]], 0, 3)

Output: 0

Example 3

Input: strongest_route(3, [[0, 1, 0.4]], 0, 2)

Output: 0

Hints

Hint 1

Multiplying by a number between 0 and 1 never increases a value, so extending a route can never make it more reliable. This is the same monotonic behavior that makes Dijkstra work for non-negative distances.

Hint 2

Adapt Dijkstra: replace addition with multiplication, and always expand the node with the largest known probability. In Python, push negated probabilities onto heapq to simulate a max-heap.

Hint 3

Only push a neighbor when the new probability is strictly greater than the best one recorded so far. This skips zero-probability links, self-loops and useless cycles, and you can ignore stale heap entries when popping.