Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: 7 servers are joined by cables one at a time. Count the connected groups at the end and how many cables were redundant (joined two servers already connected).
Problem: 7 servers are joined by cables one at a time. Count the connected groups at the end and how many cables were redundant (joined two servers already connected).
def run(n, edges):
par = list(range(n))
def find(x):
while par[x] != x:
par[x] = par[par[x]]
x = par[x]
return x
comps, red = n, 0
for u, v in edges:
ru, rv = find(u), find(v)
if ru == rv:
red += 1
else:
par[ru] = rv; comps -= 1
return comps, red
c, r = run(7, [(0,3),(2,2),(5,3),(5,5),(4,5),(4,4)])
print(c, r)What is printed?- A. 4 0
- B. 4 2
- C. 5 3
- D. 4 3
Correct answer: D. 4 3
Tracing union-find with path compression over the edges in order (a self-loop (x, x) always counts as redundant since find(x) == find(x)) gives 4 final components and 3 redundant cables.
More Coding Interview Problems questions
- What is the length of the longest common subsequence of "BDACDBED" and "DEEAAC"?
- Fractional knapsack, capacity 18 (items can be split). Items (weight, value): (6, 11), (5, 10), (3, 15), (6, 5). Using the greedy…
- Using the merge-sort inversion-count technique (count, during each merge step, how many left-half elements are greater than the current…
- Using a min-heap of size k (push each element, pop when size exceeds k, so the heap always holds the k largest seen so far), what is the k…
- Problem: Dijkstra's algorithm (array-based, pick the unvisited vertex with smallest tentative distance each round) computes shortest…
- What is the length of the longest common subsequence of "ADDDBEEE" and "DDCCCCDB"?