Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Find the path from node 0 to node 3 with the maximum product of edge success probabilities (Dijkstra on −log p, or a max-heap on the product).

Problem: Find the path from node 0 to node 3 with the maximum product of edge success probabilities (Dijkstra on −log p, or a max-heap on the product).
import heapq
def best(n, edges, s, t):
    g = [[] for _ in range(n)]
    for (u, v), p in edges: g[u].append((v, p)); g[v].append((u, p))
    prob = [0.0] * n; prob[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 < prob[u]: continue
        for v, w in g[u]:
            if p * w > prob[v]: prob[v] = p * w; heapq.heappush(h, (-prob[v], v))
    return 0.0
print(best(4, [((0,1),0.9),((1,3),0.5),((0,2),0.6),((2,3),0.9),((1,2),0.8)], 0, 3))
What is printed?
  1. A. 0.45
  2. B. 0.54
  3. C. 0.648
  4. D. 0.6

Correct answer: C. 0.648

Candidates: 0→1→3 = 0.45; 0→2→3 = 0.54; 0→1→2→3 = 0.9 × 0.8 × 0.9 = 0.648. Multiplying probabilities ≤ 1 can only decrease a path's value, so the Dijkstra-style greedy is valid, and the longer path wins with 0.648.

More Coding Interview Problems questions

Exams that ask this topic