Data Structures & AlgorithmsVery hardIBM · Deloitte pattern
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, [(1,2),(4,4),(4,2),(0,3),(6,6),(6,4),(2,5),(4,5),(3,2)])
print(c, r)What is printed?- A. 1 1
- B. 1 2
- C. 1 3
- D. 2 3
Correct answer: C. 1 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 1 final components and 3 redundant cables.
More Coding Interview Problems questions
- Using the merge-sort inversion-count technique (count, during each merge step, how many left-half elements are greater than the current…
- What is the length of the longest common subsequence of "ACEACCEBD" and "DBEADDEA"?
- Using the merge-sort inversion-count technique (count, during each merge step, how many left-half elements are greater than the current…
- Using the merge-sort inversion-count technique (count, during each merge step, how many left-half elements are greater than the current…
- Using the merge-sort inversion-count technique (count, during each merge step, how many left-half elements are greater than the current…
- What is the length of the longest common subsequence of "AEEBDCCC" and "BEBEADE"?