Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Count the friend groups

Medium · Target 15 minutes · Graphs · Type asked atAmazonGoldman Sachs

There are n people. isConnected[i][j] is 1 if person i knows person j and 0 otherwise; the matrix is symmetric and its diagonal is 1. Knowing is shared through friends: if a knows b and b knows c, then a, b and c are in the same group. Return the number of groups.

Examples

InputOutputWhy
isConnected = [[1,1,0],[1,1,0],[0,0,1]]2{0, 1} and {2}.
isConnected = [[1,0,0],[0,1,0],[0,0,1]]3Nobody knows anybody else.
isConnected = [[1,0,0,1],[0,1,1,0],[0,1,1,1],[1,0,1,1]]10 knows 3, 3 knows 2, 2 knows 1: one chain.

Constraints

  • 1 ≤ n ≤ 200
  • isConnected[i][j] is 0 or 1
  • isConnected[i][i] = 1 and the matrix is symmetric

Hints

Hint 1

The matrix is an adjacency matrix: person i's friends are the columns of row i holding a 1.

Hint 2

Count connected components: every time you meet a person not yet in any group, search from them and mark their whole group.

Hint 3

Union-find works equally well: union every pair (i, j) with a 1, then count the roots.

Where people lose marks

  • Counting direct friendships (the number of 1s) instead of groups.
  • Reading only the upper triangle and missing connections, or double-counting pairs.
  • Forgetting that a person alone is a group of one.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.