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?
  1. A. 3
  2. B. 7
  3. C. 6
  4. 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

Exams that ask this topic