Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE
Problem: All-pairs shortest paths with Floyd–Warshall on a 4-node directed graph (INF = no path).
Problem: All-pairs shortest paths with Floyd–Warshall on a 4-node directed graph (INF = no path).
INF = float("inf")
def floyd(n, edges):
d = [[0 if i == j else INF for j in range(n)] for i in range(n)]
for u, v, w in edges: d[u][v] = min(d[u][v], w)
for k in range(n):
for i in range(n):
for j in range(n):
if d[i][k] + d[k][j] < d[i][j]: d[i][j] = d[i][k] + d[k][j]
return d
d = floyd(4, [(0, 1, 5), (1, 2, 2), (2, 0, 1), (0, 3, 10), (2, 3, 3)])
print(d[0][3], d[1][0], d[3][0])What is printed?- A. 8 3 inf
- B. 10 6 inf
- C. 10 3 inf
- D. 10 3 10
Correct answer: C. 10 3 inf
0 → 3: direct 10 versus 0 → 1 → 2 → 3 = 5 + 2 + 3 = 10 – a tie, so 10. 1 → 0: 1 → 2 → 0 = 3. Node 3 has no outgoing edges, so 3 → 0 stays INF (edges are directed). The k loop must be outermost: it means 'paths using only intermediate nodes 0..k'. O(n³).
More Coding Interview Problems questions
- Problem: n computers and a list of cables; you may unplug any cable and reconnect it between any two computers. Minimum moves to connect…
- Problem: Given equations like "a==b" and "b!=c" over single-letter variables, can all hold at once? Union all '==' pairs first, then check…
- Problem: A 3-wheel lock starts at "000"; each move turns one wheel by ±1 (9 wraps to 0). Some codes are dead (the lock jams). Find the…
- Problem: Shortest paths from node 1 in a weighted DAG (negative edges allowed): topologically sort with Kahn's algorithm, then relax edges…
- Problem: An investor starts with capital w and may finish at most k projects; project i needs capital[i] to start and adds profits[i] when…
- Problem: A single CPU receives tasks (enqueue time, duration). When idle it starts the available task with the shortest duration (ties…