A city's junctions are numbered 0 to n - 1, and every street is one-way. A district is a largest group of junctions in which every junction can drive to every other one. Every junction belongs to exactly one district, possibly on its own.
Write two functions that take n and streets, an array of [from, to] pairs.
findDistricts(n, streets) returns the districts as arrays of junctions. Each district is sorted ascending, and the districts are sorted by their smallest junction.
streetsToConnectAll(n, streets) returns the fewest new one-way streets that would let every junction reach every other junction. It returns 0 when that is already true, including when n is 0 or 1.
Rules:
Streets may repeat, and a street may start and end at the same junction.
If n is not a non-negative safe integer, streets is not an array, or a street is not a pair of integers, throw a TypeError. If a street names a junction outside 0 to n - 1, throw a RangeError.
Maps can have 100,000 junctions and 200,000 streets. Searching from every junction is quadratic, and a recursive search over a 100,000-junction chain overflows the call stack.
const streets = [[0, 1], [1, 2], [2, 0], [1, 3], [3, 4], [4, 5], [5, 3], [6, 5]];findDistricts(7, streets); // [[0, 1, 2], [3, 4, 5], [6]]streetsToConnectAll(7, streets); // 2: districts {0,1,2} and {6} have no way in, {3,4,5} no way outfindDistricts(3, []); // [[0], [1], [2]]streetsToConnectAll(3, []); // 3: for example 0 → 1 → 2 → 0streetsToConnectAll(3, [[0, 1], [1, 2], [2, 0]]); // 0
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.