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?- A. 0.9
- B. 0.6
- C. 0.45
- 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
- Problem: Board game on squares 1..n: roll a die (1–6); landing on the foot of a ladder or the head of a snake moves you to its other end…
- Problem: Find the bug: Kahn's algorithm is used to schedule build steps, but nobody checks whether a cycle exists. What does it return for…
- Problem: n, q ≤ 2·10⁵ operations of two kinds: add v to every a[l..r], and ask for sum a[l..r]. A Fenwick tree with two arrays supports…
- Problem: For n = 2·10⁵, compute Σ over all subarrays of (max − min). Sum of maxima minus sum of minima, each via monotonic stacks with…
- Problem: Adjacent piles in a row are merged two at a time; merging costs the combined size. Minimise the total cost (interval DP over [i…
- Problem: Rain on a height grid flows to a neighbour with height ≤ the current cell. The west/north edge touches one sea, the east/south…