Count Separate Friend Groups Given a List of Friendship Pairs

Last updated: November 29, 2026

Quick Overview

Given n users labeled 0 to n-1 and a list of undirected friendship pairs, return the number of separate friend groups, where a group is a maximal set of users connected through friendship chains.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Easy

0

0

0 solved


Given n users labeled 0 to n-1 and a list of undirected friendship pairs, return the number of separate friend groups, where a group is a maximal set of users connected through friendship chains.

Connected components on the social graph is a natural Meta warm-up, phrased in the style of the phone screen. The interviewer checks that you build an adjacency list, traverse each unvisited user once, and know union-find as an alternative when edges stream in.

What the Interviewer Expects
  • Builds an adjacency list from the pairs
  • Runs BFS or iterative DFS from each unvisited node
  • Counts isolated users as their own group
  • Avoids recursion depth issues on large graphs
  • Mentions union-find for streaming edges
Key Topics to Cover
Graphs
BFS
Connected components
Union-find
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you answer the size of the largest group?
  • If friendships arrive as a stream, how do you keep the count current?
  • How would you handle a graph too large for one machine?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: integer n and list of [u, v] pairs. Output: number of connected components. Users with no friends count as a group of one. n up to 10^5, so the traversal must be linear and must not rely on...

High-Level Design

Build an adjacency list. Keep a seen array. Loop over every user; when one is unseen, increment the group count and BFS from it, marking every reachable user. Each user and each edge is processed a ...


Submit Your Answer
Markdown supported