Algorithms · Level 3 Graphs

Union-Find

Count how many separate networks remain as each cable is plugged in, with union-find and short parent chains so every lookup stays fast.

  • a parent per item, the root names the group
  • join two groups by linking their roots
  • shorten chains as you walk them

Union-find gives each item a parent; the root of its chain names its group. Joining two groups points one root at the other. Trap: without shortening chains as you walk them, long chains make every lookup slow.

parent = {"a": "a", "b": "a", "c": "b"}
def find(x):
    while parent[x] != x:
        x = parent[x]
    return x
find("c")  # 'a': c → b → a

Write networks_after(n, cables): computers are numbered 0 to n - 1. After each (a, b) cable is plugged in, record how many separate networks there are, and return that list. Example: networks_after(4, [(0, 1), (2, 3), (1, 0)]) → [3, 2, 2].

solution.py
Test Suites Pending
Output