ByteByteGo logo
menuProblems List

Merging Communities

Hard

There are n people numbered from 0 to n - 1 , with each person initially belonging to a separate community. When two people from different communities connect, their communities merge into a single community.

Your goal is to write two functions:

  • connect(x: int, y: int) -> None: Connects person x with person y and merges their communities.
  • get_community_size(x: int) -> int: Returns the size of the community which person x belongs to.

Example:

Input: n = 5,
       [
         connect(0, 1),
         connect(1, 2),
         get_community_size(3),
         get_community_size(0),
         connect(3, 4),
         get_community_size(4),
       ]
Output: [1, 3, 2]

You can practice coding exercises online by logging into bytebytego.com on your laptop.