Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Find the minimum total cost to connect all offices (minimum spanning tree) using Kruskal's algorithm.
Problem: Find the minimum total cost to connect all offices (minimum spanning tree) using Kruskal's algorithm.
def kruskal(n, edges):
p = list(range(n))
def f(x):
while p[x] != x: p[x] = p[p[x]]; x = p[x]
return x
total = used = 0
for w, u, v in sorted(edges):
a, b = f(u), f(v)
if a != b:
p[a] = b; total += w; used += 1
return total if used == n - 1 else -1
print(kruskal(5, [(4, 0, 1), (1, 0, 2), (3, 1, 2), (2, 1, 3), (5, 2, 3), (7, 3, 4), (6, 2, 4)]))What is printed?- A. 13
- B. 12
- C. 11
- D. 16
Correct answer: B. 12
Sorted edges: 1 (0–2), 2 (1–3), 3 (1–2), 4 (0–1, skipped: cycle), 5 (2–3, skipped), 6 (2–4), 7 (skipped). Total 1 + 2 + 3 + 6 = 12 with n − 1 = 4 edges. O(E log E).
More Coding Interview Problems questions
- Problem: Find the length of the shortest transformation from a start word to an end word, changing one letter at a time, every…
- Problem: Determine whether a graph can be coloured with two colours so that no edge joins equal colours (bipartite). python from…
- Problem: Count the number of shortest paths (fewest edges) from node 0 to node n − 1 in an unweighted graph. python from collections…
- Problem: In a grid, 0 is open and 1 is a wall. Find the shortest path length (in cells) from the top-left to the bottom-right moving in 8…
- Problem: Each cell of a grid holds 0 (empty) or 1. Return a grid of the distance from each cell to its nearest 0. python from collections…
- Problem: A city grid has V = 10⁵ junctions; every road takes either 0 minutes (flyover) or 1 minute. What is the most efficient way to get…