KatInterview

Count Clusters of Linked Playlists from a Match Grid

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsgraphconnected-componentsdfs

Last updated

Count connected components in an undirected graph given as an n x n adjacency matrix, where links chain together transitively.

A music app has n playlists, numbered from 0 to n - 1. You are given an n x n grid match made of 0s and 1s that describes which playlists are directly linked.

  • match[i][j] == 1 means playlists i and j are directly linked.
  • match[i][j] == 0 means they are not directly linked.

Links chain together: if playlist A is linked to B and B is linked to C, then A, B and C all belong to the same cluster, even if A and C have no direct link.

A cluster is a maximal set of playlists in which any two members are connected by a chain of direct links. Every playlist belongs to exactly one cluster, and a playlist with no links to others forms a cluster on its own.

Return the total number of clusters.

The grid is symmetric: match[i][j] == match[j][i] for all i, j. Diagonal entries do not affect the answer. If the grid is empty (n = 0), return 0.

Constraints

  • 0 <= n <= 200
  • match is an n x n grid; each entry is 0 or 1
  • match[i][j] == match[j][i]
  • The answer is the number of clusters as an integer

Examples

Example 1

Input: count_playlist_clusters([[1, 1, 0], [1, 1, 0], [0, 0, 1]])

Output: 2

Example 2

Input: count_playlist_clusters([[1, 1, 0, 0], [1, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 1]])

Output: 2

Example 3

Input: count_playlist_clusters([[1, 0, 0], [0, 1, 0], [0, 0, 1]])

Output: 3

Hints

Hint 1

Think of each playlist as a node and each 1 in the grid as an undirected edge. What does a cluster correspond to in this graph?

Hint 2

Scan playlists in order. When you reach one you have not seen yet, it begins a new cluster. Then explore everything reachable from it and mark all of it as seen.

Hint 3

With a grid input, finding a node's neighbors means scanning its whole row. Use an explicit stack or queue rather than recursion to avoid depth problems on long chains, and mark nodes as seen when you add them.