An office network is made of switches joined by cables. If the cables form a loop, broadcast messages circle forever and the network floods, so a diagnostic tool needs to find a loop and show the technician exactly which switches are on it.
Switches are numbered 0 to n - 1. Each entry of links is a cable [a, b] between switches a and b. Cables are undirected, there may be several cables between the same two switches, and a cable may connect a switch to itself. The network can be split into several separate parts.
Write two functions:
hasLoop(n, links) returns true if the cables contain a loop, otherwise false.
findLoop(n, links) returns null when there is no loop. Otherwise it returns one loop as an array of distinct switches [v0, v1, …, vk] such that each switch is joined by a cable to the next one, and vk is joined to v0, with every step using a different cable. Any loop and any starting point or direction is accepted.
Rules:
A cable [a, a] is a loop by itself: return [a].
Two cables between a and b form a loop: return [a, b] or [b, a]. A single cable between them is not a loop.
Throw a TypeError if links is not an array of two-element arrays, and a RangeError if n is not a non-negative integer or a cable names a switch that is not an integer from 0 to n - 1.
Do not change links. Networks can have 200,000 switches and cables, including one long chain, so the solution must be O(n + links) and must not use one recursive call per switch.
// 0 - 1 - 2 - 3// | |// 5 - 4 6 - 7findLoop(8, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 2], [6, 7]]);// [2, 3, 4, 5], or the same loop from another start or in reverse, such as [5, 4, 3, 2]hasLoop(4, [[0, 1], [1, 2], [1, 3]]); // false: a tree has no loopfindLoop(3, [[0, 1], [1, 2], [2, 2]]); // [2]: a cable from switch 2 to itselffindLoop(2, [[0, 1], [1, 0]]); // [0, 1] or [1, 0]: two separate cables
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
6
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.