Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

The connection that closes a loop

Medium · Target 15 minutes · Graphs · Type asked atGoogleAmazon

A tree on nodes 1 to n had one extra edge added between two of its nodes, so the n edges below contain exactly one cycle. edges[i] = [a, b] is an undirected edge with a < b.

Return an edge whose removal leaves a tree on all n nodes. If several edges qualify, return the one that appears last in edges.

Examples

InputOutputWhy
edges = [[1,2],[1,3],[2,3]][2, 3]Any of the three edges breaks the triangle; [2, 3] comes last.
edges = [[1,2],[2,3],[3,4],[1,4],[1,5]][1, 4]The cycle is 1–2–3–4–1. [1, 5] is not on it.
edges = [[1,2],[2,3],[1,3],[3,4]][1, 3]The last edge on the cycle, not the last edge overall.

Constraints

  • 3 ≤ n ≤ 1000
  • edges.length = n
  • 1 ≤ a < b ≤ n; no edge repeats
  • The graph is connected

Hints

Hint 1

Add the edges one at a time and keep track of which nodes are already connected.

Hint 2

The first edge whose two ends are already connected closes the cycle.

Hint 3

Why is that also the last cycle edge in the list? Every edge before it was needed to connect something.

Where people lose marks

  • Returning the last edge of the whole list rather than the last edge on the cycle.
  • Forgetting that nodes are numbered from 1: the parent array needs n + 1 entries.
  • A union-find without path compression or union by size, which is O(n) per find on a chain.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.