Phase 1: Which edge in the cycle is redundant? Look at the graph.

The Uninvited Guest

A tree with n nodes has exactly n-1 edges. This graph has n nodes and n edges — one too many. Somewhere in the graph, one edge was added after the tree was complete. That edge created a cycle. Your job: find and return it.

I tried brute force first — remove each edge, check if the graph is still connected, put it back. It worked, but it was O(E*(V+E)) and deeply unsatisfying. Then I realized something: I was looking for a needle in a haystack when the problem hands you the needle at the door — if you process edges in the right order.

But first, let us feel the problem. Here is the simplest case: a triangle. Three nodes, three edges. The cycle is obvious. Which edge is redundant?

FIG. 1 — EDGES: [[1,2],[1,3],[2,3]]. ALL THREE FORM A CYCLE. WHICH ONE TO REMOVE?
123

Pick the redundant edge — the one that should be removed: