CodingNodes / Graphs / Redundant Connection System design Space play · ←→ step · R restart

Problem

A connected graph without circles (a tree) has nodes numbered 1 to n. One extra undirected edge was then added between two different nodes that were not already joined by an edge. The result is the list edges, where edges[i] = [a, b] is an edge between nodes a and b.

Return an edge that can be removed so that the rest is a tree again. If several edges qualify, return the one that appears last in the input.

Constraints

  • n = edges.length, 3 ≤ n ≤ 1000
  • 1 ≤ a, b ≤ n and a ≠ b
  • No edge appears twice, and the whole graph is connected

Examples: pick one to animate

Solutions

TimeO(n · α(n)) SpaceO(n)

Time: Each of the n edges does two finds and at most one merge. With union by size and path halving each costs almost constant time (the inverse Ackermann function α).

Space: The parent and size arrays hold n + 1 numbers each.

Give every node its own set and add the edges in input order. An edge whose two ends already have the same root means they were connected by earlier edges, so this edge closes the circle: return it. Because every edge before it joined two different pieces, this is the last circle edge in the list. Union by size and path halving keep each step almost constant time.