Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find a redundant edge that, when removed, leaves a tree (return the last such edge in input order).
Problem: Find a redundant edge that, when removed, leaves a tree (return the last such edge in input order).
def redundant(edges):
p = list(range(len(edges) + 1))
def f(x):
while p[x] != x: p[x] = p[p[x]]; x = p[x]
return x
for u, v in edges:
a, b = f(u), f(v)
if a == b: return [u, v]
p[a] = b
print(redundant([[1, 2], [1, 3], [2, 3]]), redundant([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]))What is printed?- A. [1, 2] [1, 4]
- B. [2, 3] [1, 5]
- C. [1, 3] [3, 4]
- D. [2, 3] [1, 4]
Correct answer: D. [2, 3] [1, 4]
Add edges one by one; the first edge whose endpoints are already connected closes the cycle, and since a tree plus one edge has exactly one cycle, it is the last cycle edge in input order. Near O(n α(n)).
More Coding Interview Problems questions
- Problem: Return the alien-dictionary letter order from a sorted list of words (Kahn's algorithm, ties alphabetical). python import heapq…
- Problem: Count how many nodes are 'safe' (every path from them ends at a terminal node) in a directed graph. python def safe(g): color =…
- Problem: Find the minimum effort path in a grid where effort is the maximum absolute height difference between consecutive cells. python…
- Problem: Return the number of steps to reach the exit of a maze grid ('.' open, '+' wall) from an entrance, where an exit is an open…
- Problem: Count paths modulo 10⁹ + 7 from the top-left to the bottom-right of a 3 × 3 board whose centre is blocked, moving right, down or…
- Problem: Find the maximum number of points you can collect in a grid going right/down from top-left to bottom-right and then reconstruct…