|
| 1 | +/*--------------------------------------------- |
| 2 | + Time Complexity: O(n * m * logn) + O(mlogm) |
| 3 | + Space Complexity: O(m) |
| 4 | +-----------------------------------------------*/ |
| 5 | + |
| 6 | +class DisJointSet { |
| 7 | +public: |
| 8 | + vector<int> size, parent; |
| 9 | + |
| 10 | + DisJointSet(int n) { |
| 11 | + size.resize(n, 1); |
| 12 | + parent.resize(n); |
| 13 | + for(int i = 0; i < n; i++) parent[i] = i; |
| 14 | + } |
| 15 | + |
| 16 | + int findUParent(int node) { |
| 17 | + if(parent[node] == node) return node; |
| 18 | + return parent[node] = findUParent(parent[node]); |
| 19 | + } |
| 20 | + |
| 21 | + void UnionBySize(int u, int v) { |
| 22 | + int ult_u = findUParent(u); |
| 23 | + int ult_v = findUParent(v); |
| 24 | + if(ult_u == ult_v) return; |
| 25 | + if(size[ult_u] < size[ult_v]) { |
| 26 | + parent[ult_u] = ult_v; |
| 27 | + size[ult_v] += size[ult_u]; |
| 28 | + } else { |
| 29 | + parent[ult_v] = ult_u; |
| 30 | + size[ult_u] += size[ult_v]; |
| 31 | + } |
| 32 | + } |
| 33 | +}; |
| 34 | + |
| 35 | +class Solution { |
| 36 | +public: |
| 37 | + bool intersect(vector<int> &a, vector<int> &b, int k) { |
| 38 | + int i = 0, j = 0; |
| 39 | + int numCommon = 0; |
| 40 | + while(i < a.size() && j < b.size()) { |
| 41 | + if (a[i] == b[j]) { |
| 42 | + i += 1; |
| 43 | + j += 1; |
| 44 | + numCommon += 1; |
| 45 | + } |
| 46 | + else if(a[i] > b[j]) j += 1; |
| 47 | + else i += 1; |
| 48 | + } |
| 49 | + return numCommon >= k; |
| 50 | + } |
| 51 | + |
| 52 | + int numberOfComponents(vector<vector<int>>& properties, int k) { |
| 53 | + int n = properties.size(); |
| 54 | + int m = properties[0].size(); |
| 55 | + |
| 56 | + for(int i = 0; i < n; i++) { |
| 57 | + sort(properties[i].begin(), properties[i].end()); |
| 58 | + |
| 59 | + unordered_set<int> visited; |
| 60 | + vector<int> newArray; |
| 61 | + |
| 62 | + for(int j = 0; j < m; j++) { |
| 63 | + if(visited.find(properties[i][j]) == visited.end()) { |
| 64 | + newArray.push_back(properties[i][j]); |
| 65 | + visited.insert(properties[i][j]); |
| 66 | + } |
| 67 | + } |
| 68 | + properties[i] = newArray; |
| 69 | + } |
| 70 | + |
| 71 | + DisJointSet ds(n); |
| 72 | + |
| 73 | + for(int i = 0; i < n; i++) { |
| 74 | + for(int j = i + 1; j < n; j++) { |
| 75 | + if(!intersect(properties[i], properties[j], k)) continue; |
| 76 | + ds.UnionBySize(i, j); |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + int numComponents = 0; |
| 81 | + for(int i = 0; i < n; i++) { |
| 82 | + if(ds.findUParent(i) == i) numComponents += 1; |
| 83 | + } |
| 84 | + return numComponents; |
| 85 | + } |
| 86 | +}; |
| 87 | + |
| 88 | +/* |
| 89 | +Question Link: https://leetcode.com/problems/properties-graph/ |
| 90 | +Author: M.R.Naganathan |
| 91 | +*/ |
0 commit comments