Skip to the code
+10 XP

#415 Count Separate Chat Groups

easy

A chat app wants to show how many separate groups its users form. Users are numbered 0 to n - 1, and pairs[i] = [a, b] means a and b have chatted. Two users are in the same group if you can get from one to the other through a chain of chats.

Write countGroups(n, pairs) that returns the number of separate groups. A user who has never chatted is a group of one.

Example 1

Input: n = 5, pairs = [[0,1],[1,2],[3,4]]
Output: 2

Users 0, 1, and 2 form one group; 3 and 4 form another.

Example 2

Input: n = 3, pairs = []
Output: 3

Nobody has chatted, so each user is alone.

Constraints

  • 1 <= n <= 10^5
  • 0 <= pairs.length <= 2 * 10^5
  • 0 <= a, b < n
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).