Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
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, [(3,6),(3,2),(3,1),(6,6),(0,2),(1,6),(6,6),(6,2),(4,3)])
print(c, r)What is printed?- A. 3 4
- B. 2 3
- C. 2 2
- D. 2 4
Correct answer: D. 2 4
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 2 final components and 4 redundant cables.
More Coding Interview Problems questions
- 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…
- What is the length of the longest common subsequence of "ECAAEEDAE" and "BEEDEDD"?
- Using the merge-sort inversion-count technique (count, during each merge step, how many left-half elements are greater than the current…
- Fractional knapsack, capacity 16 (items can be split). Items (weight, value): (3, 8), (7, 6), (3, 8), (6, 8). Using the greedy…
- Fractional knapsack, capacity 15 (items can be split). Items (weight, value): (5, 14), (6, 9), (2, 9), (5, 13). Using the greedy…
- Fractional knapsack, capacity 12 (items can be split). Items (weight, value): (3, 12), (6, 9), (3, 13), (5, 9), (5, 6). Using the greedy…