ORIGINAL CODING QUESTION
First redundant network cable
Cables between n rooms are installed one at a time in the listed order. Return the 1-based position of the first cable whose two ends were already linked through earlier cables; a cable from a room to itself is always redundant. Return 0 if every cable links two previously separate groups.
Original exercise · medium. Editorial role relevance does not imply a company has asked this question.
Input and output
n m, then m vertex pairs (u,v). Vertices are zero-based. Pairs are listed in installation order.
Constraints
1 ≤ n ≤ 30; 0 ≤ m ≤ 100; room IDs in [0,n).
Example 1
Input
4 4 0 1 1 2 2 0 2 3
Output
3
Rooms 2 and 0 are already linked through room 1 when the third cable arrives.
Example 2
Input
3 2 0 1 1 2
Output
0
Both cables join separate groups.
Explain your approach
Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?
Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.
Hint 1
A cable is redundant exactly when its ends are already in the same group.
Hint 2
A disjoint-set (union-find) structure answers "same group?" quickly.
Hint 3
Check find(u) === find(v) before uniting, and stop at the first match.
Practice this question
Save your work privately, explain decisions and return to your revision queue.
Open practice workspaceBrowse the question library →