#339 · Data structures · Intermediate · 85 XP · about 18 min
There are n computers, numbered 0 to n - 1, and none of them are connected. Technicians lay cables one at a time, and the cable (a, b) connects computers a and b. Computers connected directly or through other computers form one network, and a computer on its own is a network of one.
Write groups_after_each(n, links) that returns a list with one tuple per cable in links: (networks, largest), the number of separate networks and the number of computers in the biggest one, right after that cable is laid.
groups_after_each(5, [(0, 1), (2, 3), (1, 0), (1, 3)]) # returns [(4, 2), (3, 2), (3, 2), (2, 4)] groups_after_each(3, [(0, 0)]) # returns [(3, 1)]
In the first example the third cable changes nothing, because 1 and 0 are already in the same network. The last cable joins the networks {0, 1} and {2, 3}.
A network can grow to 100,000 computers, more levels than Python lets a function call itself. If you walk up to a network's leader, do it with a loop rather than with recursion.
First solves only, ranked by stars and then time.