A tree with n nodes, labelled 1 to n, had one extra edge added between two of its nodes. The result is given as edges, a list of n undirected edges [a, b] with a < b. No edge appears twice.
Return an edge you could delete so that the remaining edges form a tree on all n nodes again. Several edges may work; if so, return the one that comes last in edges.
Example 1
Input: edges = [[1, 3], [3, 4], [1, 2], [2, 4]] Output: [2, 4] Why: the loop is 1-3-4-2-1, and [2, 4] is its last edge listed
1 more example and the constraints
Example 2
Input: edges = [[1, 2], [2, 3], [1, 3], [3, 4], [4, 5]] Output: [1, 3] Why: 1, 2 and 3 form the loop; 4 and 5 hang off it
Constraints
- 3 ≤ n ≤ 1,000, and edges has exactly n entries
- 1 ≤ a < b ≤ n for every edge [a, b]
- No repeated edges, and the whole graph is connected
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Search before each edgeO(n²)
- Union-FindO(n·α(n))
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 edges | Verdict |
|---|---|---|---|
| Search before each edge | O(n²) | Passes; repeats the same searches | |
| Union-Find | O(n·α(n)) | Best; one near-constant check per edge |
n = number of nodes (and edges); α is the inverse Ackermann function, below 5 for any real input.
Edge cases to test
- Smallest loop. [[1, 2], [2, 3], [1, 3]]: three nodes in a triangle, answer [1, 3].
- Loop through every node. A ring 1-2-3-4-5-1 has every edge on the loop; return the last one listed.
- Extra edge listed first. If the edge that later looks redundant comes first in the input, the answer is still the loop edge read last.
- Nodes hanging off the loop. Edges like [3, 4] and [4, 5] in Example 2 are never on the loop and are never returned.
Common mistakes
- Returning the first edge of the loop in the input, instead of the one that closes it, which is the last.
- Comparing
parent[u]withparent[v]directly instead of comparing their roots withfind. - Sizing the parent array as n when the labels run from 1 to n, so node n is out of range.
How to talk through it
- 1Clarify. Are nodes labelled 1 to n? If several edges would work, which one should I return?
- 2Give the simple version. Before adding each edge, search to see whether its ends are already connected; say it is O(n²).
- 3Name the real question. It is only ever “are these two already in the same group?”, which is what Union-Find answers.
- 4Code Union-Find. Write find with path halving, then loop over the edges: same root means return the edge, otherwise union.
- 5Test out loud. Run the triangle, and a case where the loop is listed in a scrambled order.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?