Count Clusters of Linked Playlists from a Match Grid
Trees & GraphsAuto-graded · 17 test casesLast 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] == 1means playlistsiandjare directly linked.match[i][j] == 0means 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 <= 200matchis ann x ngrid; each entry is0or1match[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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the playlists as nodes of an undirected graph, with an edge between i and j whenever match[i][j] == 1. Because links chain transitively, a cluster is exactly a connected component, so the task is to count connected components.
Loop over the playlists from 0 to n - 1. Whenever you reach a playlist that has not been seen yet, it must belong to a cluster not yet counted, so increment the counter. Then run an iterative depth-first search from it, scanning each popped node's row in the grid to find unseen neighbors, and mark everything reachable as seen. Marking a node when it is pushed (not when it is popped) ensures no node enters the stack twice.
Why it is correct
- A search from a start node reaches precisely the nodes connected to it by a chain of links, which is its whole cluster, and never leaves it because it only follows edges.
- After the search, every member of that cluster is marked seen, so the outer loop cannot start a second search inside it.
- Each cluster's lowest-numbered member cannot be reached by any earlier search (otherwise it would share a cluster with an earlier start), so every cluster triggers exactly one increment.
- Diagonal entries only point a node at itself, which is already seen, so they have no effect. An empty grid never enters the loop and returns
0.
Complexity
- Time: O(n^2), since each node is processed once and each processing step scans a row of length
n. - Space: O(n) for the seen array and the stack, excluding the input.
An equivalent alternative is union-find, merging the sets of every linked pair and counting the remaining sets.
Reference solution
from typing import List
def count_playlist_clusters(match: List[List[int]]) -> int:
n = len(match)
seen = [False] * n
clusters = 0
for start in range(n):
if seen[start]:
continue
clusters += 1
seen[start] = True
stack = [start]
while stack:
node = stack.pop()
for other in range(n):
if match[node][other] == 1 and not seen[other]:
seen[other] = True
stack.append(other)
return clusters