Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: A tree on nodes 1..n received one extra edge. Return the LAST edge in the input whose removal leaves a tree (union-find).
Problem: A tree on nodes 1..n received one extra edge. Return the LAST edge in the input whose removal leaves a tree (union-find).
def redundant(edges):
par = list(range(len(edges) + 1))
def f(x):
while par[x] != x: x = par[x]
return x
for a, b in edges:
ra, rb = f(a), f(b)
if ra == rb: return [a, b]
par[ra] = rb
print(redundant([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]))What is printed?- A. [1, 5]
- B. [3, 4]
- C. [1, 2]
- D. [1, 4]
Correct answer: D. [1, 4]
Edges 1–2, 2–3, 3–4 connect 1..4 in a chain; 1–4 then joins two nodes already connected, closing the cycle 1-2-3-4-1. Because union-find processes edges in order, the first edge found inside the cycle is also the last cycle edge in the input.
More Coding Interview Problems questions
- Problem: Replace each word of a sentence by its shortest root from a dictionary (if any root is a prefix). python def replace(roots…
- Problem: Find the shortest palindrome obtainable by adding characters only in FRONT of s, using the KMP failure function of s + '#' +…
- Problem: Is s made of one substring repeated two or more times? Trick: check whether s occurs in (s + s) with the first and last…
- Problem: Delete the fewest characters so that no two letters have the same (nonzero) frequency. python from collections import Counter def…
- Problem: An array of n + 1 integers holds values 1..n with exactly one value repeated (possibly several times). Find it in O(1) extra…
- Problem: Find all values appearing more than ⌊n/3⌋ times with the extended Boyer–Moore vote (two candidates), then verify. python def…