CodePark/ problems / Count the Networks
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Union-find (disjoint sets)

Count the Networks

easyabout 15 minutes in an interview

An office has n computers numbered 0 to n - 1. You get a list of cables, where each cable [a, b] links computer a and computer b in both directions.

Computers that can reach each other through one or more cables are on the same network. A computer with no cables is a network on its own.

Return the number of separate networks.

  • 1 ≤ n ≤ 100,000 and there are at most 100,000 cables.
  • Every computer number in cables is between 0 and n - 1.
  • The same cable may appear more than once, and a cable may link a computer to itself. Neither changes the answer.
Input: n = 6, cables = [[0, 1], [1, 2], [3, 4], [2, 0]] Output: 3Networks {0, 1, 2}, {3, 4} and {5}. The cable [2, 0] links two computers that were already on one network.
Input: n = 4, cables = [] Output: 4
Input: n = 3, cables = [[0, 1], [1, 2]] Output: 1