Count Similar Photo Groups
Company: Bytedance
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of graph connectivity and equivalence relations, requiring recognition of connected components from an adjacency-matrix representation of pairwise similarity.
Constraints
- 0 <= n <= 200
- `isSimilar` is an `n x n` matrix
- Each value in `isSimilar` is either `0` or `1`
- `isSimilar[i][j] == isSimilar[j][i]` for all valid `i`, `j`
Examples
Input: []
Expected Output: 0
Explanation: There are no photos, so there are no groups.
Input: [[1]]
Expected Output: 1
Explanation: A single photo forms one group by itself.
Input: [[1,1,0],[1,1,0],[0,0,1]]
Expected Output: 2
Explanation: Photos 0 and 1 are connected, while photo 2 is alone, giving 2 groups.
Input: [[1,0,0],[0,1,0],[0,0,1]]
Expected Output: 3
Explanation: No two different photos are similar, so each photo is its own group.
Input: [[1,1,0,0],[1,1,1,0],[0,1,1,0],[0,0,0,1]]
Expected Output: 2
Explanation: Photos 0, 1, and 2 are all connected through transitivity, and photo 3 is separate.
Input: [[1,0,0,1,0],[0,1,1,0,0],[0,1,1,0,0],[1,0,0,1,0],[0,0,0,0,1]]
Expected Output: 3
Explanation: The groups are {0,3}, {1,2}, and {4}, so the answer is 3.
Hints
- Think of each photo as a node in an undirected graph, and each `1` as an edge.
- Count how many times you need to start a new DFS or BFS from an unvisited photo.