Redundant Connection

35 min · findRedundantConnection()

A road network began as a perfect tree. Then one extra road was added, and now exactly one loop exists. Which road should you undo?

You're given edges, an ordered list of undirected connections. The graph uses nodes labeled 1 through n, where n == edges.length. Before one extra edge was added, the graph was a tree.

Return an edge whose removal restores a tree. A redundant edge is one you can remove without disconnecting the graph. Every edge on the single cycle — a route that leaves a node and returns to it without reusing an edge — qualifies. When several do, return the one that appears last in edges. Preserve that edge's endpoint order.

Constraints

  • 3 <= n <= 1_000
  • edges.length == n
  • Every edge contains two labels in the range 1..n.
  • There are no self-loops and no duplicate undirected edges.
  • The graph is a tree plus exactly one extra edge, so it contains exactly one cycle.

Hints

Try every removal

Work backward through edges. Remove one candidate, then test whether the remaining n - 1 edges connect all n nodes without a cycle.

Replay the construction

Add the edges in their given order. A tree edge always joins two groups that were separate. What changes when you reach the last edge on the cycle?

Ask the roots

Union-find tells you whether two endpoints are already connected. The first edge whose endpoints share a root is the answer.

Follow-up

If a much larger stream could contain several extra edges, how would you report every edge that closes a cycle as it arrives?

Visible cases

Examples

Example 1

ready
Input
edges = [
  [
    1,
    2
  ],
  [
    1,
    3
  ],
  [
    2,
    3
  ]
]
Expected
[
  2,
  3
]
Why
[2, 3] appears last among the three removable cycle edges

Example 2

ready
Input
edges = [
  [
    1,
    2
  ],
  [
    2,
    3
  ],
  [
    3,
    4
  ],
  [
    1,
    4
  ],
  [
    1,
    5
  ]
]
Expected
[
  1,
  4
]
Why
the fourth edge closes the 1-2-3-4 loop

Example 3

ready
Input
edges = [
  [
    1,
    2
  ],
  [
    2,
    3
  ],
  [
    3,
    1
  ],
  [
    3,
    4
  ]
]
Expected
[
  3,
  1
]
Why
the tail to node 4 isn't part of the cycle

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite