Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Edges arrive one by one; report the first edge that creates an ODD cycle (making the graph non-bipartite), using union-find with parity.
Problem: Edges arrive one by one; report the first edge that creates an ODD cycle (making the graph non-bipartite), using union-find with parity.
def first_odd(n, edges):
par, par_x = list(range(n)), [0] * n
def find(x):
if par[x] == x: return x, 0
r, p = find(par[x]); par[x] = r; par_x[x] ^= p
return r, par_x[x]
for i, (u, v) in enumerate(edges):
ru, pu = find(u); rv, pv = find(v)
if ru == rv:
if pu == pv: return i
else: par[ru] = rv; par_x[ru] = pu ^ pv ^ 1
return -1
print(first_odd(6, [(0,1),(1,2),(2,3),(3,0),(3,4),(4,5),(5,3),(0,2)]))What is printed?- A. 3
- B. 7
- C. 6
- D. -1
Correct answer: C. 6
Parity stores whether a node's colour differs from its root's. 0-1-2-3-0 is a 4-cycle (even), fine. Edge 6 (5, 3) closes the triangle 3-4-5, and its endpoints already have the same parity, so index 6 is reported. (0, 2) would also create an odd cycle, but later.
More Coding Interview Problems questions
- Problem: Total weight of a MAXIMUM spanning tree (Kruskal with edges sorted in decreasing order). python edges =…
- Find the bug: Dijkstra (finalising a node when first popped) is run on a graph with a NEGATIVE edge. Compare with Bellman–Ford. python…
- Problem: Topological order produced by DFS (append a node after all its descendants, then reverse). python g = {0: [2, 1], 1: [3], 2: [3…
- Problem: Maximum bipartite matching between workers (left) and jobs (right) with Kuhn's augmenting-path algorithm. python adj = {0: [0…
- Problem: Maximum flow from s = 0 to t = 5 with Edmonds–Karp (BFS augmenting paths). python from collections import deque cap = [[0]6 for…
- Problem: Does an undirected connected graph have an Euler path / Euler circuit? (count odd-degree vertices) python from collections import…