Find the Extra Edge
Company: Apple
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of graph theory concepts—cycle formation and edge connectivity—and the competency in applying graph algorithm techniques to identify and remove a redundant edge in an undirected graph.
Constraints
- n == len(edges)
- 3 <= n <= 1000
- 1 <= u, v <= n
- u != v
- The graph is connected and contains exactly one cycle
Examples
Input: ([[1, 2], [1, 3], [2, 3]],)
Expected Output: [2, 3]
Explanation: This is the smallest valid case. The third edge closes the cycle 1-2-3-1, so removing [2, 3] restores a tree.
Input: ([[1, 4], [1, 2], [2, 3], [3, 4]],)
Expected Output: [3, 4]
Explanation: All four edges are part of the cycle. Any of them could be removed, so we return the one that appears last in the input: [3, 4].
Input: ([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]],)
Expected Output: [1, 4]
Explanation: The cycle is 1-2-3-4-1. The last edge from that cycle in the input is [1, 4].
Input: ([[1, 2], [2, 3], [3, 4], [4, 5], [2, 5]],)
Expected Output: [2, 5]
Explanation: The cycle is 2-3-4-5-2, and [2, 5] is the last edge from that cycle in the input.
Hints
- A tree has no cycles. As you process edges one by one, what does it mean if the two endpoints are already connected?
- Use a Disjoint Set Union (Union-Find) structure to track connected components efficiently while scanning the edges in input order.