You are given a 2D integer array properties having dimensions n x m and an integer k.
Define a function intersect(a, b) that returns the number of distinct integers common to both arrays a and b.
Construct an undirected graph where each index i corresponds to properties[i]. There is an edge between node i and node j if and only if intersect(properties[i], properties[j]) >= k, where i and j are in the range [0, n - 1] and i != j.
Return the number of connected components in the resulting graph.
Example 1:
Input:properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1
Output:3
Explanation:
The graph formed has 3 connected components:
Example 2:
Input:properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2
Output:1
Explanation:
The graph formed has 1 connected component:
Example 3:
Input:properties = [[1,1],[1,1]], k = 2
Output:2
Explanation:
intersect(properties[0], properties[1]) = 1, which is less than k. This means there is no edge between properties[0] and properties[1] in the graph.
Constraints:
1 <= n == properties.length <= 100
1 <= m == properties[i].length <= 100
1 <= properties[i][j] <= 100
1 <= k <= m
Solutions
Solution 1: Hash Table + DFS
Thinking
Two nodes are adjacent iff their property sets share at least \(k\) values. \(n,m\le 100\), so we build the graph and count components.
Lists may repeat; converting to sets keeps the intersection from being over-counted.
Compare every pair, add undirected edges, and DFS/BFS to count components.
We first convert each attribute array into a hash table and store them in a hash table array \(ss\). We define a graph \(g\), where \(g[i]\) stores the indices of attribute arrays that are connected to \(\textit{properties}[i]\).
Then, we iterate through all attribute hash tables. For each pair of attribute hash tables \((i, j)\) where \(j < i\), we check whether the number of common elements between them is at least \(k\). If so, we add an edge from \(i\) to \(j\) in the graph \(g\), as well as an edge from \(j\) to \(i\).
Finally, we use Depth-First Search (DFS) to compute the number of connected components in the graph \(g\).
The time complexity is \(O(n^2m)\), and the space complexity is \(O(nm)\), where \(n\) is the length of the attribute arrays and \(m\) is the number of elements in an attribute array.