[LeetCode] Properties Graph

3493. Properties Graph

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.

c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
int uf[111];
int find(int u) {
return uf[u] == u ? u : uf[u] = find(uf[u]);
}
void uni(int u, int v) {
int pu = find(u), pv = find(v);
uf[pu] = uf[pv] = min(pu,pv);
}
bool intersect(bitset<100>& A, bitset<100>& B, int k) {
return (A & B).count() >= k;
}
public:
int numberOfComponents(vector<vector<int>>& properties, int k) {
iota(begin(uf), end(uf), 0);
int n = properties.size(), res = 0;
vector<bitset<100>> bs(properties.size());
for(int i = 0; i < n; i++) {
for(auto& p : properties[i]) bs[i][p-1] = 1;
}
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if(intersect(bs[i], bs[j], k)) uni(i,j);
}
}
for(int i = 0; i < n; i++) if(find(i) == i) res++;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/03/23/PS/LeetCode/properties-graph/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Related Issues not found

Please contact @SongHayoung to initialize the comment