Data Structures & AlgorithmsHardProduct company OA

Problem: Each link succeeds with a probability; find the most reliable path from 0 to 3 (maximise the product). Dijkstra works with a max-heap because multiplying by p ≤ 1 never increases the value.

Problem: Each link succeeds with a probability; find the most reliable path from 0 to 3 (maximise the product). Dijkstra works with a max-heap because multiplying by p ≤ 1 never increases the value.
import heapq
def max_prob(n, edges, probs, s, t):
    adj = [[] for _ in range(n)]
    for (u, v), p in zip(edges, probs): adj[u].append((v, p)); adj[v].append((u, p))
    best = [0.0] * n; best[s] = 1.0; h = [(-1.0, s)]
    while h:
        p, u = heapq.heappop(h); p = -p
        if u == t: return round(p, 4)
        if p < best[u]: continue
        for v, q in adj[u]:
            if p * q > best[v]: best[v] = p * q; heapq.heappush(h, (-best[v], v))
    return 0.0
print(max_prob(4, [(0, 1), (1, 3), (0, 2), (2, 3), (0, 3)], [0.9, 0.8, 0.5, 0.9, 0.6], 0, 3))
What is printed?
  1. A. 0.9
  2. B. 0.6
  3. C. 0.45
  4. D. 0.72

Correct answer: D. 0.72

Paths: 0 → 1 → 3 = 0.9 × 0.8 = 0.72; 0 → 2 → 3 = 0.45; direct 0 → 3 = 0.6. Probabilities ≤ 1 make path values non-increasing, the analogue of non-negative weights, so the first time t is popped its value is final. Equivalently run ordinary Dijkstra on −log p. Picking the strongest first link (0.9 to node 1) happens to work here but not in general. O(E log V).

More Coding Interview Problems questions

Exams that ask this topic