Coding problem
The first cable that closes a loop
The task
Network engineers add cables between switches one at a time. A cable between two switches that are already connected, directly or through other cables, makes a loop, which this network must not have.
Complete FirstLoopLink(int n, int[][] links). Switches are numbered 0 to n - 1. The cables are added in the order of links, and each [a, b] joins a and b both ways. Return the first cable whose two ends were already connected before it was added, as [a, b] in the order given. Return an empty array if no cable closes a loop. A cable [a, a] closes a loop at once.
Signature
public static int[] FirstLoopLink(int n, int[][] links)
Examples
3, [[0, 1], [1, 2], [2, 0]]→[2, 0]. 2 and 0 were already connected through 1.5, [[0, 1], [1, 2], [2, 3], [3, 4]]→[]. A chain never closes a loop.
Limits: Up to 5,000 switches and 5,000 cables.
The tests check: no cables, one cable, a ring, a chain, ends joined through several cables, two groups joined without a loop, a cable [a, a], the same cable twice, a switch cabled twice, the first loop rather than a later one, and 5,000 switches.
Hints
Your code
Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;
public static class Solution
{
// The first cable whose two ends were already connected, or an empty array.
public static int[] FirstLoopLink(int n, int[][] links)
{
throw new NotImplementedException();
}
}This problem comes with TechInterviewNotes Full Access
Unlock all paid content on TechInterviewNotes.