You are given an undirected, connected, simple graph on n nodes labeled 1 through n. The graph has exactly n edges, which means it is a spanning tree plus exactly one additional edge — so it contains exactly one cycle (there are no self-loops and no repeated edges). The edges are listed in a fixed order. Imagine inserting them one at a time into an initially empty graph: exactly one edge, when inserted, connects two nodes that are already connected by previously inserted edges — that edge is the one that closes the cycle. Output that edge.
n and m. It is guaranteed that m = n and the graph satisfies the properties above.m lines: each contains two integers u and v (1-indexed) describing an undirected edge.A single line with two integers u v: the endpoints of the redundant edge, printed exactly in the order they appear on that edge's input line (do not reorder them).
Example 1
Input
4 4 1 2 2 3 3 4 1 3
Expected
1 3
Explanation
Inserting 1-2, 2-3, 3-4 builds a tree over {1,2,3,4}. Inserting 1-3 joins nodes 1 and 3, which are already connected via 1-2-3, so 1-3 closes the cycle. Output the endpoints as given: `1 3`.
Example 2
Input
5 5 2 1 3 2 2 4 5 4 5 3
Expected
5 3
Explanation
After 2-1, 3-2, 2-4, 5-4 all nodes are connected as a tree. The final edge 5-3 joins 5 and 3, already connected (5-4-2-3), so it closes the cycle. Output `5 3` in the input order.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →