question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
โŒ€
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
counting-words-with-a-given-prefix
Just 3 lines code๐Ÿคฏโค๏ธโ€๐Ÿ”ฅMost easy solutionโœ…๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ปBeats ๐Ÿ’ฏ% solutions on LeetCode๐Ÿฆโ€๐Ÿ”ฅ
just-3-lines-codemost-easy-solutionbeats-0t6b
IntuitionFirst of all on reading the question I realised that we just need to count the number of words in the given array which have given word as prefix and t
codonaut_anant_05
NORMAL
2025-01-09T15:17:05.987936+00:00
2025-01-09T15:17:05.987936+00:00
8
false
# Intuition First of all on reading the question I realised that we just need to count the number of words in the given array which have given word as prefix and then simply return that count. ![image.png](https://assets.leetcode.com/users/images/f6df6932-1062-4153-ab9a-76fe677f91ec_1736434709.4123886.png) # Approach - First create a variable of int data type named `count=0`. - Now traverse through the given vector `words` and for each word check if the starting of the word contains the given word `pref` as prefix using `substr()` function. - Increment the `count`, if the above condition is satisfied. - Finally, return `count`. # Complexity - **Time complexity:** O(n*m)โณ - **Space complexity:** O(1)๐Ÿš€ # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int count=0; for(auto x: words){ count+=(x.substr(0,pref.size())==pref); } return count; } }; ``` ๐™‹๐™ก๐™š๐™–๐™จ๐™š ๐™ช๐™ฅ๐™ซ๐™ค๐™ฉ๐™š๐Ÿ‘ ๐™ž๐™› ๐™ฎ๐™ค๐™ช ๐™›๐™ค๐™ช๐™ฃ๐™™ ๐™ž๐™ฉ ๐™๐™š๐™ก๐™ฅ๐™›๐™ช๐™ก ๐™œ๐™ช๐™ฎ๐™จ ๐™–๐™จ ๐™ž๐™ฉ ๐™ฌ๐™ค๐™ช๐™ก๐™™ ๐™š๐™ฃ๐™˜๐™ค๐™ช๐™ง๐™–๐™œ๐™š ๐™ข๐™š ๐™ฉ๐™ค ๐™ฅ๐™ค๐™จ๐™ฉ ๐™ข๐™ค๐™ง๐™š ๐™จ๐™ช๐™˜๐™ ๐™จ๐™ค๐™ก๐™ช๐™ฉ๐™ž๐™ค๐™ฃ๐™จ. ๐Ÿ˜‡
2
0
['Array', 'String', 'C++']
0
counting-words-with-a-given-prefix
Easy C++ Beats 100%
easy-c-beats-100-by-abhishek-verma01-61ku
IntuitionThe problem requires counting how many strings in the listwordsstart with a specific prefix pref. The solution involves checking each string in the lis
Abhishek-Verma01
NORMAL
2025-01-09T14:27:25.941046+00:00
2025-01-09T14:27:25.941046+00:00
9
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem requires counting how many strings in the list` words `start with a specific prefix `pref.` The solution involves checking each string in the list to see if its first few characters match the prefix. If they do, the count is incremented. # Approach <!-- Describe your approach to solving the problem. --> 1. Iterate Through Words: * Loop through each string in the `words` list. * For each word, ensure that it is at least as long as the prefix to avoid out-of-bound checks. 2. Check Prefix Using `find:` * Use the `string::find` function to determine if the prefix is present at the start of the string (i.e., at position 0). If true, increment the count. 3. Handle Edge Cases: * Skip checking if the prefix is longer than the current word, as it cannot match. 4. Return the Count: * After iterating through all words, return the total count of strings starting with the given prefix. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - O(n) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> - O(1) # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int n = words.size(); // Get the number of words in the list int count = 0; // Initialize a counter to keep track of matches // Iterate through each word in the list for (int i = 0; i < n; i++) { // If the prefix length is greater than the current word's length, // skip this word since the prefix cannot match if (pref.size() > words[i].size()) { continue; } // Check if the prefix exists at the start of the word // 'find(pref) == 0' ensures the prefix is found at index 0 if (words[i].find(pref) == 0) { count++; // Increment the counter if the prefix matches } } return count; // Return the total count of words with the prefix } }; ```
2
0
['Array', 'String', 'String Matching', 'Counting', 'C++']
0
counting-words-with-a-given-prefix
Super easy solution in python. (beats 100%) - one liner solution.
super-easy-solution-in-python-beats-100-mohhp
IntuitionHere we need to find that if the string present in array starts with the given prefix.ApproachThe approach for this is super easy. We just need to loop
shwet_46
NORMAL
2025-01-09T14:19:38.686059+00:00
2025-01-09T14:28:11.318380+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Here we need to find that if the string present in array starts with the given prefix. # Approach <!-- Describe your approach to solving the problem. --> The approach for this is super easy. We just need to loop through words list and check if it starts with given prefix using ***s.startswith()*** function. If it is true increase the count and after looping return the count. # Complexity - Time complexity: O(n*m) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def prefixCount(self, words: List[str], pref: str) -> int: c = 0 for i in words: if i.startswith(pref): c += 1 return c ``` # One liner solution ๐Ÿ—ฟ ``` class Solution: def prefixCount(self, words: List[str], pref: str) -> int: return sum(1 for x in words if x.startswith(pref)) ``` **Hope so you like this !**
2
0
['Array', 'String', 'String Matching', 'Python3']
0
counting-words-with-a-given-prefix
beats:100%, 1 line javascript solution
1-line-javascript-solution-by-baesumin-1fyi
IntuitionApproachComplexity Time complexity: O(n*k) Space complexity: O(n) Code
baesumin
NORMAL
2025-01-09T13:25:54.821457+00:00
2025-01-09T23:54:11.135260+00:00
16
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n*k) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {string[]} words * @param {string} pref * @return {number} */ var prefixCount = function (words, pref) { return words.filter(word => word.startsWith(pref)).length }; ```
2
0
['Array', 'String', 'String Matching', 'JavaScript']
0
counting-words-with-a-given-prefix
Beginner friendly, beats 100%
beginner-friendly-beats-100-by-akshitha_-4q7p
IntuitionTo check every word in the words[] array starts with the given prefix pref.Approach Initialize a variable int count=0 to keep the track of the words in
Akshitha_Naverse
NORMAL
2025-01-09T13:20:12.865889+00:00
2025-01-09T13:20:12.865889+00:00
6
false
# Intuition To check every word in the `words[]` array starts with the given prefix `pref`. <!-- Describe your first thoughts on how to solve this problem. --> # Approach - Initialize a variable `int count=0` to keep the track of the words in the `words[]` array which start with the given prefix `pref`. - Simply check if every word in the `words[]` array starts with the given prefix `pref` and increment the `count` variable if so. - Use the `str.startsWith()` method to check if the given prefix `pref` is a prefix of the current word from the `words[]` array. - Return the `count`. <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int prefixCount(String[] words, String pref) { int count=0; for(String word:words) { if(word.startsWith(pref)) count++; } return count; } } ```
2
0
['Java']
0
counting-words-with-a-given-prefix
Simple Cpp Solution
simple-cpp-solution-by-arpita_sat-m5mq
ApproachIterate through elements of words and just compare te starting characters of each word with the pref string.Complexity Time complexity: O(n*m) where n =
arpita_sat
NORMAL
2025-01-09T12:56:29.333850+00:00
2025-01-09T12:56:29.333850+00:00
11
false
# Approach <!-- Describe your approach to solving the problem. --> Iterate through elements of words and just compare te starting characters of each word with the pref string. # Complexity - Time complexity: O(n*m) where n = number of words and m = length of pref string <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int ans=0; for(int i=0; i<words.size(); i++) { bool flag=true; for(int j=0; j<pref.length(); j++) { if(pref[j] != words[i][j]) { flag=false; break; } } if(flag) ans++; } return ans; } }; ```
2
0
['C++']
0
counting-words-with-a-given-prefix
My minimal and easy solution in c++
my-minimal-and-easy-solution-in-c-by-mo7-sqz7
My Code
Mo7amed_3bdelghany
NORMAL
2025-01-09T12:43:30.387880+00:00
2025-01-09T12:43:30.387880+00:00
14
false
# My Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int count = 0, n = pref.size(); for(auto it: words){ if(it.substr(0, n) == pref) count++; } return count; } }; ```
2
0
['String Matching', 'C++']
0
counting-words-with-a-given-prefix
Easy solution || Beats 100%
easy-solution-beats-100-by-shantanusaxen-safv
IntuitionMatching every character of pref with the the prefixes of strings present in words array.Approach Iterate through every element in the array. And initi
ShantanuSaxena
NORMAL
2025-01-09T11:49:49.036811+00:00
2025-01-09T11:49:49.036811+00:00
8
false
![{B1FAC10B-CDD1-4F1F-BB50-349308744B30}.png](https://assets.leetcode.com/users/images/07a653ba-1329-4b36-bff2-0028411d5452_1736422431.2019923.png) # Intuition Matching every character of pref with the the prefixes of strings present in words array. # Approach 1. Iterate through every element in the array. And initialize a counter cnt to return the final answer. 2. Now check is the pref is a prefix of words[i] or not. If it is a prefix than increase the cnt. 3. To check initialize a pointer (j = 0) over pref and string and check one by one if they match than increment the pointer j (j++) otherwise return false. # Complexity - Time complexity: **O(n.m)** where n = size of array and m = length of pref string. - Space complexity: **O(1)** <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool check(string s1, string s2){ int j = 0; while(j < s2.size()){ if(s1[j] != s2[j]) return false; else j++; } return true; } int prefixCount(vector<string>& words, string pref) { int n = words.size(); int cnt = 0; for(int i = 0; i < n; i++){ if(check(words[i], pref)) cnt++; } return cnt; } }; ``` Upvote if it helps :)
2
0
['C++']
0
counting-words-with-a-given-prefix
JAVA | Faster Than 100% | Runtime : 1ms
java-faster-than-100-runtime-1ms-by-07_d-esah
Complexity Time complexity: O(N) Space complexity: O(N) Code
07_deepak
NORMAL
2025-01-09T11:09:07.026557+00:00
2025-01-09T11:09:07.026557+00:00
10
false
# Complexity - Time complexity: **O(N)** <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: **O(N)** <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int prefixCount(String[] words, String pref) { int n=pref.length(),c=0; for(String i:words){ if(i.length()>=n && i.substring(0,n).equals(pref)){ c+=1; } } return c; } } ```
2
0
['Java']
0
counting-words-with-a-given-prefix
Very Easy Detailed Solution ๐Ÿ”ฅ || ๐Ÿ”ฅ Beats 100% || ๐ŸŽฏ Two Approaches
very-easy-detailed-solution-beats-100-tw-92ow
Approach 1: Helper Function (isPrefix): Checks if a string (str1) starts with another string (pref) by comparing the substring of str1 of length equal to pref
chaturvedialok44
NORMAL
2025-01-09T10:31:50.065115+00:00
2025-01-09T10:31:50.065115+00:00
28
false
# Approach 1: <!-- Describe your approach to solving the problem. --> 1. **Helper Function (isPrefix):** - Checks if a string (str1) starts with another string (pref) by comparing the substring of str1 of length equal to pref. - If the length of str1 is less than the length of pref, it immediately returns false since pref cannot be a prefix. 2. **Main Function (prefixCount):** - Iterates through the words array. - For each word, it calls the isPrefix function to check if the word starts with pref. - If isPrefix returns true, the counter ans is incremented. 3. **Return Value:** - The total count of words with the specified prefix is returned. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $O(n*n2)$ - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $O(n*n2)$ # Code ```java [] class Solution { private boolean isPrefix(String str1, String pref) { int n1 = str1.length(), n2 = pref.length(); if (n1 < n2) { return false; } return str1.substring(0, n2).equals(pref); } public int prefixCount(String[] words, String pref) { int n = words.length, ans = 0; for(int i=0; i<n; i++){ if(isPrefix(words[i], pref)){ ans++; } } return ans; } } ``` # Approach 2 : Optimized <!-- Describe your approach to solving the problem. --> 1. **Loop Through the Words:** - Iterate through each string in the words array. 2. **Length Check:** - If the length of the current string (s) is less than the length of pref, it cannot have pref as a prefix, so mark it with flag = false. 3. **Character-by-Character Comparison:** - If the length is sufficient, compare characters of the word and the prefix one by one up to the length of pref. - If any character doesn't match, set flag = false and break out of the inner loop. 4. **Count Matching Prefixes:** - If flag remains true, increment the counter ans. 5. **Return the Count:** - Finally, return the total count of words that match the prefix. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $O(n*m)$ - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $O(1)$ # Code ```java [] class Solution { public int prefixCount(String[] words, String pref) { int n = words.length; int m = pref.length(); int ans = 0; for(int i=0; i<n; i++){ String s = words[i]; boolean flag = true; if(s.length() < m){ flag = false; } else{ for(int j=0; j<s.length() && j<m; j++){ if(s.charAt(j) != pref.charAt(j)){ flag = false; break; } } } if(flag){ ans++; } } return ans; } } ```
2
0
['Array', 'String', 'String Matching', 'Counting', 'Java']
2
properties-graph
[C++ & Java] DSU || Simple and easy to understand solution
dsu-simple-and-easy-to-understand-soluti-x4vt
Intuition find if the nodes are connected or not. we just need to check each item of each property to be checked in the other item property, if its present or n
kreakEmp
NORMAL
2025-03-23T04:02:11.601008+00:00
2025-03-23T05:26:26.063743+00:00
2,376
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> - find if the nodes are connected or not. we just need to check each item of each property to be checked in the other item property, if its present or not. To do this further we can create a map of set and push each item to it. the other way around is sort each property and then iteratively match each item form both items property. - Once we can evaluate connectedness, then simply initialise the total connected count to total items ( assuming all the items are disconnected at the begining). Then keep on reducing the count as we merge two distict group together. # Approach - Insert all item's property to the map of set data structure - Iterate over all possible combinations of nodes - check if they are connected or not ( standard DSU - find, add code) - if connected then, reduce the count if the two nodes are distinct groups before combining to single group. # Complexity - Time complexity: O(n.n.p) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n.p) <!-- Add your space complexity here, e.g. $$O(n)$$ --> Here n is total node count and p is the length of property # Code ```cpp [] bool isConnected(unordered_map<int, unordered_set<int>>& mp, int k, int i, int j){ for(auto t: mp[i]) k -= (mp[j].find(t) != mp[j].end())?1:0; return (k <= 0); } int find(int node, vector<int>& par){ return par[node] = ((par[node] == node)?node: find(par[node], par)); } int add(int a, int b, vector<int>& par){ int pa = find(a, par), pb = find(b, par); par[pb] = pa; return (pa != pb)?1:0; // return 1 if bothe are in different group before ese return 0 } int numberOfComponents(vector<vector<int>>& p, int k) { int count = p.size(); vector<int> par(p.size(), -1); unordered_map<int, unordered_set<int>> mp; for(int i = 0; i < par.size(); ++i) par[i] = i; for(int i = 0; i < p.size(); ++i){ // create the lookup map for(int j = 0; j < p[i].size(); ++j) mp[i].insert(p[i][j]); } for(int i = 0; i < p.size(); ++i){ for(int j = i+1; j < p.size(); ++j){ if(isConnected(mp, k, i, j)) count -= add(i, j, par); // check connected or not, if connected then add them and if we are merging two disconnected group then reduce the total count by 1 } } return count; } ``` ```Java [] boolean isConnected(Map<Integer, Set<Integer>> map, int k, int i, int j){ for(Integer t: map.get(i)) k -= (map.get(j).contains(t))?1:0; return (k <= 0); } int find(int node, int[] par){ System.out.println(node + " " + par[node]); return par[node] = ((par[node] == node)?node: find(par[node], par)); } int add(int a, int b, int[] par){ int pa = find(a, par), pb = find(b, par); par[pb] = pa; return (pa != pb)?1:0; // return 1 if bothe are in different group before ese return 0 } int numberOfComponents(int[][] p, int k) { int count = p.length; int[] par = new int[p.length]; for(int i = 0; i < par.length; ++i) par[i] = i; Map<Integer, Set<Integer>> map = new HashMap<>(); for(int i = 0; i < p.length; ++i){ // create the lookup map for(int j = 0; j < p[i].length; ++j) map.computeIfAbsent(i, key -> new HashSet<>()).add(p[i][j]); } for(int i = 0; i < p.length; ++i){ for(int j = i+1; j < p.length; ++j){System.out.println(i + " " + j); if(isConnected(map, k, i, j)) count -= add(i, j, par); // check connected or not, if connected then add them and if we are merging two disconnected group then reduce the total count by 1 } } return count; } ```` --- <span style="color:green"> <b>Here is an article of my last interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon: </b> </span> https://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted ---
14
0
['C++', 'Java']
5
properties-graph
โšกEASYโœ… AND SHORT CODE๐Ÿจ|| BEATS ๐Ÿ’ฏ๐Ÿš€||ใ€C++/Java/Py3/JSใ€‘โŒšCLEAN EXPLANATION โŒš
easy-and-short-code-beats-cjavapy3js-cle-iik9
IntuitionWe need to construct an undirected graph where each node represents a row in the properties matrix. An edge exists between two nodes if the intersectio
Fawz-Haaroon
NORMAL
2025-03-23T06:06:55.957822+00:00
2025-03-23T17:03:58.954297+00:00
1,399
false
# **Intuition** We need to construct an undirected graph where each node represents a row in the `properties` matrix. An edge exists between two nodes if the intersection of their respective lists contains at least `k` common elements. The problem then reduces to counting the number of connected components in this graph using the **Union-Find (Disjoint Set Union, DSU)** data structure. --- # **Approach** 1. **Initialize Union-Find (DSU) and Presence Array:** - Maintain a `parent` array where each node is initially its own parent. - Use a `cnt` array to store the presence of numbers in each row for quick lookups. 2. **Mark Presence of Numbers in Each Row:** - Iterate through each row and mark the numbers present in `cnt[i]`. 3. **Check for Intersections Between Rows:** - For every row `i`, compare it with all previous rows `j`. - Count the number of common elements between `properties[i]` and `properties[j]`. - If the common element count is **at least `k`**, merge the two rows using Union-Find. 4. **Count Connected Components:** - Traverse the `parent` array and count the number of unique roots (nodes that are their own parent). --- # **Complexity Analysis** - **Preprocessing Presence Array:** `O(n m)` - **Checking Intersections:** `O(nยฒ . 100)` (since we check up to 100 numbers per pair) - **Union-Find Operations:** `O(n . alpha(n))`, where `alpha(n)` is the inverse Ackermann function (almost constant). # Overall Time Complexity: O(nยฒ + n * m) # Overall Space Complexity: O(n) --- # **Code** (commented explanation) ```cpp [] class Solution { public: int cnt[155][155]; // Stores presence of numbers in each row int par[155]; // Union-Find parent array // Find function with path compression int fin(int x) { if (par[x] == x) return x; return par[x] = fin(par[x]); } int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); // Initialize Union-Find and presence array for (int i = 0; i < n; i++) { par[i] = i; // Initially, each node is its own parent memset(cnt[i], 0, sizeof(cnt[i])); // Reset presence array // Mark numbers present in the current row for (int num : properties[i]) cnt[i][num] = 1; // Compare with previous rows to check intersection count for (int j = 0; j < i; j++) { int commonCt = 0; // Count how many numbers appear in both rows for (int num = 1; num <= 100; num++) { if (cnt[i][num] && cnt[j][num]) commonCt++; } // Merge components if common elements >= k if (commonCt >= k) par[fin(j)] = fin(i); } } // Count the number of connected components int compCt = 0; for (int i = 0; i < n; i++) { if (fin(i) == i) compCt++; }return compCt; } }; ``` ```python3 [] class Solution: def find(self, x, parent): if parent[x] == x: return x parent[x] = self.find(parent[x], parent) # Path compression return parent[x] def numberOfComponents(self, properties, k): n = len(properties) parent = [i for i in range(n)] cnt = [[0] * 101 for _ in range(n)] # Presence array for i in range(n): for num in properties[i]: cnt[i][num] = 1 for j in range(i): common_count = sum(1 for num in range(1, 101) if cnt[i][num] and cnt[j][num]) if common_count >= k: parent[self.find(j, parent)] = self.find(i, parent) return sum(1 for i in range(n) if self.find(i, parent) == i) ``` ```java [] class Solution { find(x, parent) { if (parent[x] === x) return x; return parent[x] = this.find(parent[x], parent); } numberOfComponents(properties, k) { let n = properties.length; let parent = Array.from({ length: n }, (_, i) => i); let cnt = Array.from({ length: n }, () => Array(101).fill(0)); for (let i = 0; i < n; i++) { for (let num of properties[i]) { cnt[i][num] = 1; } for (let j = 0; j < i; j++) { let commonCount = 0; for (let num = 1; num <= 100; num++) { if (cnt[i][num] && cnt[j][num]) { commonCount++; } } if (commonCount >= k) { parent[this.find(j, parent)] = this.find(i, parent); } } } return parent.filter((_, i) => this.find(i, parent) === i).length; } } ``` ```javascript [] /** * @param {number[][]} properties * @param {number} k * @return {number} */ var numberOfComponents = function(properties, k) { let n = properties.length; let parent = Array.from({ length: n }, (_, i) => i); let cnt = Array.from({ length: n }, () => Array(101).fill(0)); // Find function with path compression const find = (x) => { if (parent[x] === x) return x; return parent[x] = find(parent[x]); }; // Step 1: Fill presence array for (let i = 0; i < n; i++) { for (let num of properties[i]) { cnt[i][num] = 1; } // Step 2: Compare with previous rows for (let j = 0; j < i; j++) { let commonCount = 0; for (let num = 1; num <= 100; num++) { if (cnt[i][num] && cnt[j][num]) { commonCount++; } } // Step 3: Union if commonCount >= k if (commonCount >= k) { parent[find(j)] = find(i); } } } // Step 4: Count connected components let componentCount = 0; for (let i = 0; i < n; i++) { if (find(i) === i) { componentCount++; } } return componentCount; }; ``` # **Code** (withot comments) ```cpp [] class Solution { public: int cnt[155][155]; int parent[155]; int find(int x) { if (parent[x] == x) return x; return parent[x] = find(parent[x]); } int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); for (int i = 0; i < n; i++) { parent[i] = i; memset(cnt[i], 0, sizeof(cnt[i])); for (auto v : properties[i]) cnt[i][v] = 1; for (int j = 0; j < i; j++) { int h = 0; for (int l = 1; l <= 100; l++) { if (cnt[i][l] && cnt[j][l]) h++; }if (h >= k) parent[find(j)] = find(i); } } int res = 0; for (int i = 0; i < n; i++){ if (find(i) == i) res++; }return res; } }; ``` ```python3 [] class Solution: def find(self, x, parent): if parent[x] == x: return x parent[x] = self.find(parent[x], parent) return parent[x] def numberOfComponents(self, properties, k): n = len(properties) parent = [i for i in range(n)] cnt = [[0] * 101 for _ in range(n)] for i in range(n): for num in properties[i]: cnt[i][num] = 1 for j in range(i): common_count = sum(1 for num in range(1, 101) if cnt[i][num] and cnt[j][num]) if common_count >= k: parent[self.find(j, parent)] = self.find(i, parent) return sum(1 for i in range(n) if self.find(i, parent) == i) ``` ```java [] class Solution { find(x, parent) { if (parent[x] === x) return x; return parent[x] = this.find(parent[x], parent); } numberOfComponents(properties, k) { let n = properties.length; let parent = Array.from({ length: n }, (_, i) => i); let cnt = Array.from({ length: n }, () => Array(101).fill(0)); for (let i = 0; i < n; i++) { for (let num of properties[i]) { cnt[i][num] = 1; } for (let j = 0; j < i; j++) { let commonCount = 0; for (let num = 1; num <= 100; num++) { if (cnt[i][num] && cnt[j][num]) { commonCount++; } } if (commonCount >= k) { parent[this.find(j, parent)] = this.find(i, parent); } } } return parent.filter((_, i) => this.find(i, parent) === i).length; } } ``` ```javascript [] var numberOfComponents = function(properties, k) { let n = properties.length; let parent = Array.from({ length: n }, (_, i) => i); let cnt = Array.from({ length: n }, () => Array(101).fill(0)); const find = (x) => { if (parent[x] === x) return x; return parent[x] = find(parent[x]); }; for (let i = 0; i < n; i++) { for (let num of properties[i]) { cnt[i][num] = 1; } for (let j = 0; j < i; j++) { let commonCount = 0; for (let num = 1; num <= 100; num++) { if (cnt[i][num] && cnt[j][num]) { commonCount++; } } if (commonCount >= k) { parent[find(j)] = find(i); } } } let componentCount = 0; for (let i = 0; i < n; i++) { if (find(i) === i) { componentCount++; } } return componentCount; }; ``` ``` โœจ AN UPVOTE WILL BE APPRECIATED ^_~ โœจ ```
12
1
['Union Find', 'Graph', 'Matrix', 'Prefix Sum', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
1
properties-graph
UnionFind with rank + bitset|C++ beats 100%
unionfind-with-rank-bitsetc-beats-9314-b-fitl
IntuitionSolveed by Union find with optimation by rank. To implement the interesection by using bitsetApproach[LC1971 uses this UnionFind class with rank. Pleas
anwendeng
NORMAL
2025-03-23T10:13:39.681488+00:00
2025-03-24T23:48:07.771054+00:00
393
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Solveed by Union find with optimation by rank. To implement the interesection by using bitset # Approach <!-- Describe your approach to solving the problem. --> [LC1971 uses this UnionFind class with rank. Please turn English subtitles if necessary] [https://youtu.be/B1GQlUN08lk?si=DpfxrPBWc-t5eSPi](https://youtu.be/B1GQlUN08lk?si=DpfxrPBWc-t5eSPi) 1. UnionFind has 2 versions; 1 has `components` as member variable which is computed during performing `Union` action; other is the normal UnionFind with `rank` 2. 2 different versions for function `intersect` which computes the number of elements in $A\cap B$ by using `bitset` # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $O(n^2m)$ where $m=average_{x\in nums}(|x|)$ - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $O(101)$ # Code 0~4ms||beats 100% ```cpp [] class UnionFind { public: char root[100], rank[100], components; UnionFind(int N): components(N){ iota(root, root+N, 0); fill(rank, rank+N, 1); } int Find(int x) { return (x==root[x]) ? x : root[x] = Find(root[x]); } bool Union(int x, int y) {//Union by rank int rX = Find(x), rY = Find(y); if (rX == rY) return 0; if (rank[rX] > rank[rY]) swap(rX, rY); root[rX] = rY; if (rank[rX] == rank[rY]) rank[rY]++; components--; return 1; } }; class Solution { public: static int intersect(const auto& A, const auto& B){ return (A&B).count(); } static int numberOfComponents(vector<vector<int>>& properties, int k) { const int n=properties.size(), m=properties[0].size(); vector<bitset<101>> A(n, 0); int i=0; for(auto& a: properties){ for(int x: a) A[i][x]=1; i++; } UnionFind G(n); int components=n; for(int i=0; i<n-1; i++){ for(int j=i+1; j<n; j++){ const auto& X=A[i]; const auto& Y=A[j]; if (intersect(X, Y)>=k){ G.Union(i, j); } } } return G.components; } }; ``` ```cpp [C++ 2nd ver] class UnionFind { public: int root[100], rank[100]; UnionFind(int N){ iota(root, root+N, 0); fill(rank, rank+N, 1); } int Find(int x) { return (x==root[x]) ? x : root[x] = Find(root[x]); } bool Union(int x, int y) {//Union by rank int rX = Find(x), rY = Find(y); if (rX == rY) return 0; if (rank[rX] > rank[rY]) swap(rX, rY); root[rX] = rY; if (rank[rX] == rank[rY]) rank[rY]++; return 1; } bool connected(int x, int y) { return Find(x) == Find(y); } }; class Solution { public: static int intersect(const vector<int>& A, const vector<int>& B){ bitset<101> a=0, b=0; for(int x: A) a[x]=1; for(int x: B) b[x]=1; return (a&b).count(); } static int numberOfComponents(vector<vector<int>>& properties, int k) { const int n=properties.size(), m=properties[0].size(); UnionFind G(n); int components=n; for(int i=0; i<n-1; i++){ for(int j=i+1; j<n; j++){ const auto& A=properties[i]; const auto& B=properties[j]; if (intersect(A, B)>=k){ components-=G.Union(i, j); // cout<<"i="<<i<<", j="<<j<<" inter="<<intersect(A, B)<<" Union="<<u<<endl; } } } return components; } }; ```
10
0
['Bit Manipulation', 'Union Find', 'C++']
3
properties-graph
C++ | Easy To Understand | DFS Must Learn For Interviews
c-easy-to-understand-dfs-must-learn-for-m1btr
Intuition The problem involves determining the number of connected components in a graph where nodes represent elements with certain properties. Two nodes are c
kirthik
NORMAL
2025-03-23T07:55:46.309614+00:00
2025-03-23T08:01:55.192337+00:00
582
false
**Intuition** The problem involves determining the number of connected components in a graph where nodes represent elements with certain properties. Two nodes are connected if they share at least k properties. Our goal is to construct this graph and then count the number of connected components. **Approach** - Build the Graph: - Each element is represented as a node. - We compare every pair of nodes to check if they have at least k common properties. - If they do, we add an edge between them, forming an adjacency list representation of the graph. - Perform DFS to Count Components: - We traverse the graph using Depth-First Search (DFS) to find all connected components. - A visited array keeps track of which nodes have been explored. - Every time we find an unvisited node, we start a new DFS traversal, counting it as a new component. **Complexity** **Time Complexity:** - Constructing the graph involves comparing all pairs of nodes, leading to **O(nยฒ โ‹… m)**, where **n** is the number of nodes and **m** is the maximum number of properties per node. - DFS traversal runs in **O(n + e)**, where **e** is the number of edges. - Overall, the time complexity is **O(nยฒ โ‹… m)**. **Space Complexity:** - The adjacency list requires **O(n + e)**. - The visited array takes **O(n)**. - The set representation of properties uses **O(n โ‹… m)**. - Overall, the space complexity is **O(nยฒ + n โ‹… m)** in the worst case. Explanation of the Code 1. build_graph function: 2. Converts the properties into sets for fast lookup. 3. Iterates through all pairs of nodes and checks if they share at least k properties. 4. If they do, an edge is added to the adjacency list. 5. dfs function: Recursively explores all connected nodes starting from a given node. 6. numberOfComponents function: Builds the graph using build_graph. Uses DFS to count the number of connected components. Code ``` class Solution { public: vector<vector<int>> build_graph(const vector<vector<int>>& p, int k) { int n = p.size(); vector<vector<int>> adj_list(n); vector<unordered_set<int>> s(n); // Convert properties to sets for fast lookup for (int i = 0; i < n; i++) { for (auto &x: p[i]) s[i].insert(x); } // Check all pairs of nodes for at least k common properties for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int common = 0; for (auto &x: s[j]) { if (s[i].count(x)) common++; if (common >= k) break; } if (common >= k) { adj_list[i].push_back(j); adj_list[j].push_back(i); } } } return adj_list; } void dfs(int node, const vector<vector<int>>& adj_list, vector<bool>& visited) { visited[node] = true; for (int neigh: adj_list[node]) { if (!visited[neigh]) { dfs(neigh, adj_list, visited); } } } int numberOfComponents(vector<vector<int>>& properties, int k) { vector<vector<int>> adj = build_graph(properties, k); int n = properties.size(); vector<bool> visited(n, false); int count = 0; for (int i = 0; i < n; i++) { if (!visited[i]) { count++; dfs(i, adj, visited); } } return count; } }; ``` ![A cute cat.webp](https://assets.leetcode.com/users/images/cc2c0fe5-2608-42d3-b1b5-726cfbe0a443_1742716906.9073727.webp)
8
0
['Depth-First Search', 'C++']
0
properties-graph
Easy & Detailed Explanationโœ… | DSU | Union - Find | C++ | Java | Python | Js
easy-detailed-explanation-dsu-union-find-6nxl
๐Ÿง  IntuitionThe problem requires finding the number of connected components in a graph where each node represents a list of elements. Two nodes are connected if
himanshu_dhage
NORMAL
2025-03-23T04:05:11.840943+00:00
2025-03-23T04:05:11.840943+00:00
947
false
# ๐Ÿง  Intuition The problem requires finding the number of connected components in a graph where each node represents a list of elements. Two nodes are connected if they share **at least k common elements**. A **union-find (disjoint set)** data structure is well-suited for this task as it efficiently merges components and finds their representatives. # ๐Ÿš€ Approach 1๏ธโƒฃ **Initialize Union-Find:** - Create two arrays: - `v1`: Parent array (stores the representative of each node). - `v2`: Rank array (used for union by rank). - Each node is initially its own parent. 2๏ธโƒฃ **Build Adjacency Map:** - Use a **hash map** (`unordered_map`) for each node to store its elements. - Helps in quickly checking common elements between nodes. 3๏ธโƒฃ **Compare Node Pairs:** - Iterate over all node pairs `(i, j)`. - Count the **common elements** between them. - If the count is **โ‰ฅ k**, merge the nodes using **union-find**. 4๏ธโƒฃ **Count Unique Components:** - Use a **set** to store unique root representatives. - The size of this set is the number of connected components. # โณ Complexity - **Time Complexity:** - Constructing the adjacency map: $$O(n \cdot m)$$ (where `m` is the average list size). - Checking common elements: $$O(n^2 \cdot m)$$ in the worst case. - Union-Find operations (amortized): $$O(\alpha(n))$$ per operation. - Overall, **approximately** $$O(n^2 \cdot m)$$. - **Space Complexity:** - **Adjacency map:** $$O(n \cdot m)$$. - **Union-Find arrays:** $$O(n)$$. - **Set for unique components:** $$O(n)$$. - **Total:** **$$O(n \cdot m)$$**. ### **Step-by-Step Explanation** ```plaintext properties = [[1,2], [2,3], [4,5]], k = 1 ``` ### Step 1: Initialize Each Node as Its Own Parent Initially, each node is its own parent: | Index (i) | Properties | Parent (v1[i]) | Rank (v2[i]) | |-----------|------------|----------------|--------------| | 0 | [1,2] | 0 | 0 | | 1 | [2,3] | 1 | 0 | | 2 | [4,5] | 2 | 0 | ### Step 2: Create an Adjacency Map Each node stores its properties in a map: | Index (i) | Properties | Frequency Map | |-----------|------------|---------------| | 0 | [1,2] | {1:1, 2:1} | | 1 | [2,3] | {2:1, 3:1} | | 2 | [4,5] | {4:1, 5:1} | ### Step 3: Compare Nodes and Merge We check each pair to see if they share at least k = 1 common element. | Pair (i, j) | Common Elements | Merge? | |-------------|----------------|------------------| | (0,1) | {2} | โœ… Yes (Union 0,1) | | (0,2) | {} | โŒ No | | (1,2) | {} | โŒ No | ### Step 4: Find Connected Components After merging, we check the unique root parents: | Index (i) | Final Parent (find(i)) | |-----------|------------------------| | 0 | 0 | | 1 | 0 | | 2 | 2 | ### Unique components are `{0, 2}`, so the final answer is **2**. ๐ŸŽฏ # Code ```cpp [] class Solution { public: // Arrays to store parent references and rank for union-find (disjoint set) vector<int> v1, v2; // Function to find the representative (root) of a set using path compression int find(int i) { if (v1[i] != i) // If i is not its own parent { v1[i] = find(v1[i]); // Recursively find the root and apply path compression } return v1[i]; // Return the root of i } // Function to unite (merge) two sets using union by rank void unite(int i, int k) { int a = find(i); // Find root of i int b = find(k); // Find root of k if (a != b) // If they belong to different sets, merge them { if (v2[a] > v2[b]) { v1[b] = a; // Attach the smaller tree (b) to the larger tree (a) } else if (v2[a] < v2[b]) { v1[a] = b; // Attach the smaller tree (a) to the larger tree (b) } else { v1[b] = a; // Merge b into a and increase rank of a v2[a]++; } } } // Function to count the number of connected components int numberOfComponents(vector<vector<int>>& p, int k) { int n = p.size(); // Number of elements (nodes) // Initialize disjoint set v1.resize(n); // Parent array v2.resize(n, 0); // Rank array (initially all 0) for (int i = 0; i < n; i++) { v1[i] = i; // Each node is its own parent initially } // Create an adjacency map to store element frequency for each node vector<unordered_map<int, int>> mp(n); for (int i = 0; i < n; i++) { for (int j : p[i]) { mp[i][j] = mp[i][j] + 1; // Count occurrences of each element in node i } } // Compare each pair of nodes to check common elements for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int cmn = 0; // Count of common elements between node i and node j // Check for common elements between node i and j for (auto it = mp[i].begin(); it != mp[i].end(); it++) { int num = it->first; if (mp[j].find(num) != mp[j].end()) // If element exists in both nodes { cmn++; } } // If the count of common elements is greater than or equal to k, merge them if (cmn >= k) { unite(i, j); } } } // Count the number of unique connected components unordered_set<int> st; for (int i = 0; i < n; i++) { st.insert(find(i)); // Insert unique root representatives into the set } return st.size(); // The number of unique roots gives the number of components } }; ``` ```javascript [] class Solution { constructor() { this.parent = new Map(); // Parent reference map this.rank = new Map(); // Rank map } // Find function with path compression find(i) { if (this.parent.get(i) !== i) { this.parent.set(i, this.find(this.parent.get(i))); // Path compression } return this.parent.get(i); } // Union function with union by rank unite(i, k) { let a = this.find(i); let b = this.find(k); if (a !== b) { if (this.rank.get(a) > this.rank.get(b)) { this.parent.set(b, a); } else if (this.rank.get(a) < this.rank.get(b)) { this.parent.set(a, b); } else { this.parent.set(b, a); this.rank.set(a, this.rank.get(a) + 1); } } } // Function to count the number of connected components numberOfComponents(p, k) { let n = p.length; // Initialize union-find structure for (let i = 0; i < n; i++) { this.parent.set(i, i); this.rank.set(i, 0); } // Create a map to store element frequency for each node let mp = new Array(n).fill(0).map(() => new Map()); for (let i = 0; i < n; i++) { for (let num of p[i]) { mp[i].set(num, (mp[i].get(num) || 0) + 1); } } // Compare each pair of nodes to check common elements for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { let cmn = 0; // Count of common elements // Count common elements for (let num of mp[i].keys()) { if (mp[j].has(num)) { cmn++; } } // If the count of common elements is >= k, merge the sets if (cmn >= k) { this.unite(i, j); } } } // Count the number of unique connected components let st = new Set(); for (let i = 0; i < n; i++) { st.add(this.find(i)); } return st.size; // The number of unique roots gives the number of components } } ``` ```python [] from collections import defaultdict class Solution: def __init__(self): self.parent = {} # Dictionary for parent references in union-find self.rank = {} # Dictionary for rank of sets def find(self, i): """Find the root of node i with path compression.""" if self.parent[i] != i: self.parent[i] = self.find(self.parent[i]) # Path compression return self.parent[i] def unite(self, i, k): """Union by rank of two sets.""" a = self.find(i) b = self.find(k) if a != b: # Merge only if they are in different sets if self.rank[a] > self.rank[b]: self.parent[b] = a elif self.rank[a] < self.rank[b]: self.parent[a] = b else: self.parent[b] = a self.rank[a] += 1 def numberOfComponents(self, p, k): n = len(p) # Number of nodes # Initialize union-find structure for i in range(n): self.parent[i] = i self.rank[i] = 0 # Create a dictionary to store element occurrences per node mp = [defaultdict(int) for _ in range(n)] for i in range(n): for num in p[i]: mp[i][num] += 1 # Compare each pair of nodes to check common elements for i in range(n): for j in range(i + 1, n): cmn = sum(1 for num in mp[i] if num in mp[j]) # If the count of common elements is >= k, merge the sets if cmn >= k: self.unite(i, j) # Count the number of unique connected components return len(set(self.find(i) for i in range(n))) ``` ```java [] import java.util.*; class Solution { // Arrays for storing parent references and rank in union-find int[] parent, rank; // Function to find the representative (root) of a set using path compression private int find(int i) { if (parent[i] != i) { // If i is not its own parent parent[i] = find(parent[i]); // Recursively find the root and apply path compression } return parent[i]; // Return the root of i } // Function to unite (merge) two sets using union by rank private void unite(int i, int k) { int a = find(i); // Find root of i int b = find(k); // Find root of k if (a != b) { // If they belong to different sets, merge them if (rank[a] > rank[b]) { parent[b] = a; // Attach the smaller tree (b) to the larger tree (a) } else if (rank[a] < rank[b]) { parent[a] = b; // Attach the smaller tree (a) to the larger tree (b) } else { parent[b] = a; // Merge b into a and increase rank of a rank[a]++; } } } // Function to count the number of connected components public int numberOfComponents(List<List<Integer>> p, int k) { int n = p.size(); // Number of nodes // Initialize union-find structure parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; // Each node is its own parent initially } // Create an adjacency map to store element frequency for each node List<Map<Integer, Integer>> mp = new ArrayList<>(); for (int i = 0; i < n; i++) { mp.add(new HashMap<>()); for (int num : p.get(i)) { mp.get(i).put(num, mp.get(i).getOrDefault(num, 0) + 1); } } // Compare each pair of nodes to check common elements for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int cmn = 0; // Count of common elements between node i and node j // Check for common elements between node i and j for (int num : mp.get(i).keySet()) { if (mp.get(j).containsKey(num)) { cmn++; } } // If the count of common elements is >= k, merge the sets if (cmn >= k) { unite(i, j); } } } // Count the number of unique connected components Set<Integer> st = new HashSet<>(); for (int i = 0; i < n; i++) { st.add(find(i)); // Insert unique root representatives into the set } return st.size(); // The number of unique roots gives the number of components } } ```
8
1
['Hash Table', 'Union Find', 'C++', 'Java', 'Python3', 'JavaScript']
1
properties-graph
Fastest C++ | Beats 100% | Easy and explained
fastest-c-beats-100-easy-and-explained-b-evwi
IntuitionApproachComplexity Time complexity: Space complexity: Code
AK200199
NORMAL
2025-03-23T07:37:22.367655+00:00
2025-03-23T07:37:22.367655+00:00
504
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class DisjointSet{ vector<int>r,p; public: DisjointSet(int n){ r=vector<int>(n); p=vector<int>(n); for(int i=0;i<n;i++)p[i]=i; } int f(int x){ if(p[x]==x)return x; return p[x]=f(p[x]); } void u(int a,int b){ a=f(a);b=f(b); if(a==b)return; if(r[a]<r[b])p[a]=b; else if(r[b]<r[a])p[b]=a; else p[b]=a,r[a]++; } }; class Solution { public: int numberOfComponents(vector<vector<int>>&A,int k){ int n=A.size(); // we can use bitset to find the intersection among all within n^2 // if we do it using set then it will take n^2*m vector<bitset<101>>bs(n); for(int i=0;i<n;i++) for(int x:A[i]) bs[i][x]=1; // Now to find the no.of componets we can use DSU DisjointSet d(n); for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ // Insert all the nodes which have edges // Edges are only if there is more than or equal to k common // elements among the 2 vectors if((bs[i]&bs[j]).count()>=k) d.u(i,j); } } // simply take a set to find the no.of unqiue ultimate parent unordered_set<int>s; for(int i=0;i<n;i++)s.insert(d.f(i)); // return the size of the set return s.size(); } }; ```
6
0
['C++']
2
properties-graph
โœ… Do as they say โœ…
do-as-they-say-by-ajay_prabhu-4puc
IntuitionTo solve this problem, I need to build a graph where nodes are connected based on the number of common elements they share. Then I need to count the co
Ajay_Prabhu
NORMAL
2025-03-23T06:27:03.450161+00:00
2025-03-23T06:27:03.450161+00:00
180
false
# Intuition To solve this problem, I need to build a graph where nodes are connected based on the number of common elements they share. Then I need to count the connected components in this graph. # Approach 1. Build an adjacency list representation of the graph: - For each pair of arrays, calculate the number of distinct common elements using a set intersection - If the intersection count is at least k, add an edge between the corresponding nodes 2. Count connected components using BFS: - Use a boolean array to keep track of visited nodes - For each unvisited node, perform BFS and mark all reachable nodes as visited - Increment the component count each time BFS is performed # Complexity - Time complexity: O(nยฒ ร— m), where n is the number of arrays and m is the maximum length of any array. We compare each pair of arrays (O(nยฒ)) and calculating the intersection takes O(m) time. - Space complexity: O(nยฒ + nm) for the adjacency list (O(nยฒ) in worst case) and set operations (O(nm)). # Code ```java class Solution { public int numberOfComponents(int[][] properties, int k) { int n = properties.length; List<List<Integer>> adj = new ArrayList<>(); for(int i = 0; i < n; i++) { adj.add(new ArrayList<>()); } // Build the graph for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { int intersectionCount = intersect(properties[i], properties[j]); if(intersectionCount >= k) { adj.get(i).add(j); adj.get(j).add(i); } } } // Count connected components int componentCount = 0; boolean[] vis = new boolean[n]; for(int i = 0; i < n; i++) { if(!vis[i]) { bfs(i, adj, vis); componentCount++; } } return componentCount; } // BFS to traverse all nodes in a connected component public void bfs(int node, List<List<Integer>> adj, boolean[] vis) { Queue<Integer> q = new LinkedList<>(); q.add(node); vis[node] = true; while(!q.isEmpty()) { int curNode = q.remove(); for(int neighbour : adj.get(curNode)) { if(!vis[neighbour]) { q.add(neighbour); vis[neighbour] = true; } } } } // Count distinct common elements between two arrays public int intersect(int[] a, int[] b) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for(int num : a) set1.add(num); for(int num : b) set2.add(num); set1.retainAll(set2); return set1.size(); } } ``` ![fa14ea89-3c60-41c2-94ef-92e1e1c20d13_1732668720.141056.webp](https://assets.leetcode.com/users/images/71e52715-b723-4d94-8fa7-6472059c3133_1742711169.4951062.webp)
6
0
['Hash Table', 'Breadth-First Search', 'Graph', 'Java']
1
properties-graph
Union-Find and Set Intersection
union-find-and-set-intersection-by-votru-enbw
First, we convert properties to sets so we can use set_intersection.Then, we go though each pair and check if they are already in the same set (find operation).
votrubac
NORMAL
2025-03-23T04:12:00.019127+00:00
2025-03-23T04:12:00.019127+00:00
556
false
First, we convert properties to sets so we can use `set_intersection`. Then, we go though each pair and check if they are already in the same set (find operation). If not, we check for the set intersection, and join these two elements. # Code ```cpp [] int find(int i, vector<int> &ds) { return ds[i] < 0 ? i : ds[i] = find(ds[i], ds); } int numberOfComponents(vector<vector<int>>& props, int k) { int n = props.size(), m = props[0].size(); vector<int> intersect(m); vector<set<int>> ps; for (const auto &p : props) ps.push_back(set<int>(begin(p), end(p))); vector<int> ds(n, -1); for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) if (int a = find(i, ds), b = find(j, ds); a != b) if (set_intersection(begin(ps[i]), end(ps[i]), begin(ps[j]), end(ps[j]), begin(intersect)) - begin(intersect) >= k) ds[b] = a; return count(begin(ds), end(ds), -1); } ```
6
0
['C++']
2
properties-graph
Use union find
use-union-find-by-thomashsiao-5n47
IntuitionWhen we look at the description carefully, we can find some hints. First, it is an undirected graph. Second, it requires the number of connected compon
ThomasHsiao
NORMAL
2025-03-23T09:15:53.995070+00:00
2025-03-23T09:17:00.179360+00:00
166
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> When we look at the description carefully, we can find some hints. First, it is an undirected graph. Second, it requires the number of connected components in the resulting graph. From the second hint, we can image we only need root for every connected graph, then union find is a good choice. And through the intersect function, we could know if they were connected, we can union them together. Then how we find all combinations? We need nested loop to find them. How we implement the intersect function? Based on the constraint, we could use two limited array(max size 101 for 1 to 100) for counting. Then we could check at every index again to count intersections by && operator, then return true if the result were larger than or equal to k. Finally, counting the parent array to find roots, and it is answer! # Approach <!-- Describe your approach to solving the problem. --> Using union find to find roots! # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> Let m means rows, and n means columns. we need to loop for all combinations, it takes O(m^2), and we need to do the intersect function will take O(n), so we need O(m^2 * n). Also, we need to find roots from parent array, it takes O(m). In sum, the time complexity is O(m^2 * n + m). - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(m) for storing rank and parent. # Code ```cpp [] class Solution { private: std::vector<int> parent; std::vector<int> rank; int find(int x) { if (parent[x] == -1) { return x; } return parent[x] = find(parent[x]); } void union_set(int x, int y) { int rx = find(x); int ry = find(y); if (rx == ry) { return; } if (rank[rx] > rank[ry]) { parent[ry] = rx; rank[rx] += rank[ry]; } else { parent[rx] = ry; rank[ry] += rank[rx]; } } bool intersect(int& k, std::vector<int>& v1, std::vector<int>& v2) { int cnt = 0; int cnt1[101]{ 0 }; int cnt2[101]{ 0 }; for (auto& v : v1) { ++cnt1[v]; } for (auto& v : v2) { ++cnt2[v]; } for (int i = 1; i <= 100; ++i) { if (cnt1[i] && cnt2[i]) { ++cnt; } } return cnt >= k; } public: int numberOfComponents(vector<vector<int>>& properties, int k) { int rows = properties.size(); int cols = properties[0].size(); parent.resize(rows, -1); rank.resize(rows, 1); for (int r = 0; r < rows; ++r) { for (int n = r + 1; n < rows; ++n) { if (intersect(k, properties[r], properties[n])) { union_set(r, n); } } } int ans = 0; for (int i = 0; i < rows; ++i) { if (parent[i] == -1) { ++ans; } } return ans; } }; ``` ```java [] class Solution { private int[] parent; private int[] rank; private int find(int x) { if (parent[x] == -1) { return x; } return parent[x] = find(parent[x]); } private void unionSet(int x, int y) { int rootX = find(x); int rootY = find(y); if (rootX == rootY) { return; } if (rank[rootX] > rank[rootY]) { parent[rootY] = rootX; rank[rootX] += rank[rootY]; } else { parent[rootX] = rootY; rank[rootY] += rank[rootX]; } } private boolean intersect(int k, int[] v1, int[] v2) { int[] count1 = new int[101]; int[] count2 = new int[101]; for (int v : v1) { count1[v]++; } for (int v : v2) { count2[v]++; } int commonCount = 0; for (int i = 1; i <= 100; i++) { if (count1[i] > 0 && count2[i] > 0) { commonCount++; } } return commonCount >= k; } public int numberOfComponents(int[][] properties, int k) { int rows = properties.length; parent = new int[rows]; rank = new int[rows]; Arrays.fill(parent, -1); Arrays.fill(rank, 1); for (int r = 0; r < rows; r++) { for (int n = r + 1; n < rows; n++) { if (intersect(k, properties[r], properties[n])) { unionSet(r, n); } } } int components = 0; for (int i = 0; i < rows; i++) { if (parent[i] == -1) { components++; } } return components; } } ``` ```python3 [] class Solution: def __init__(self): self.parent = [] self.rank = [] def find(self, x: int) -> int: if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) # Path compression return self.parent[x] def union_set(self, x: int, y: int) -> None: root_x = self.find(x) root_y = self.find(y) if root_x != root_y: if self.rank[root_x] > self.rank[root_y]: self.parent[root_y] = root_x elif self.rank[root_x] < self.rank[root_y]: self.parent[root_x] = root_y else: self.parent[root_y] = root_x self.rank[root_x] += 1 def intersect(self, k: int, v1: List[int], v2: List[int]) -> bool: counter1 = Counter(v1) counter2 = Counter(v2) common_count = sum(1 for item in counter1 if item in counter2) return common_count >= k def numberOfComponents(self, properties: List[List[int]], k: int) -> int: rows = len(properties) self.parent = list(range(rows)) # Initialize to itself self.rank = [0] * rows for r in range(rows): for n in range(r + 1, rows): if self.intersect(k, properties[r], properties[n]): self.union_set(r, n) return sum(1 for i in range(rows) if self.find(i) == i) ```
4
0
['Union Find', 'C++', 'Java', 'Python3']
0
properties-graph
๐Ÿ˜€100% User Beat | ๐Ÿ’ก DFS | Java
100-user-beat-dfs-java-by-s_a_m2003-qhmd
IntuitionApproachComplexity Time complexity: Space complexity: Code
s_a_m2003
NORMAL
2025-03-24T10:58:02.334091+00:00
2025-03-24T10:58:02.334091+00:00
52
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { Map<Integer,List<Integer>> graph = new HashMap<>(); public int numberOfComponents(int[][] properties, int k) { int v = properties.length; for(int i = 0 ; i < v; i++){ graph.put(i,new ArrayList<>()); } for(int i = 0 ; i < v; i++){ for(int j = 0; j < v; j++){ if(i != j && checkIntersection(properties[i],properties[j],k)){ addEdge(graph,i,j); } } } int cc = connectedComponent(graph, v); System.out.println(cc); return cc; } public boolean checkIntersection(int arr1[], int arr2[], int k){ Arrays.sort(arr1); Arrays.sort(arr2); int i = 0; int j = 0; Set<Integer> set = new HashSet<>(); while(i < arr1.length && j < arr2.length){ if(arr1[i] == arr2[j]){ set.add(arr1[i]); i++; j++; } else if(arr1[i] > arr2[j]){ j++; }else{ i++; } } if(set.size() >= k){ return true; } return false; } public void addEdge(Map<Integer,List<Integer>> graph, int v1, int v2){ graph.get(v1).add(v2); graph.get(v2).add(v1); } public int connectedComponent(Map<Integer,List<Integer>> graph,int v) { // one thing that you know Graph is disconnected(Some of them are connected) // to go on each starting node you have to create an array of visited array int visited[] = new int[v]; // after that i will try to find all possible diconnected component via // using visited array... int count = 0; for(int i = 0; i < visited.length; i++){ if(visited[i] == 0){ count++; dfs(graph,visited,i); } } return count; } public void dfs(Map<Integer,List<Integer>> graph, int []visited,int src){ Stack<Integer> stack = new Stack<>(); stack.push(src); while(!stack.isEmpty()){ int v = stack.pop(); if(visited[v] == 1){ continue; } visited[v] = 1; for(int nbrs : graph.get(v)){ if(visited[nbrs] != 1){ stack.push(nbrs); } } } } } ```
3
0
['Depth-First Search', 'Graph', 'Java']
1
properties-graph
Efficiently Counting Connected Components in a Graph Using DFS (Adjacency List)
efficiently-counting-connected-component-eiik
IntuitionThe problem requires us to construct a graph where each node represents a list of properties. An edge exists between two nodes if the number of common
pravardhan_100
NORMAL
2025-03-23T04:38:04.369939+00:00
2025-03-23T04:38:04.369939+00:00
199
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem requires us to construct a graph where each node represents a list of properties. An edge exists between two nodes if the number of common elements in their respective lists is at least k. Our goal is to determine the number of connected components in this graph. # Approach <!-- Describe your approach to solving the problem. --> 1. **Graph Construction**: - Iterate through all pairs of indices \((i, j)\) and check if they share at least \(k\) common elements. - If they do, add an edge between them in the adjacency list. 2. **Finding Connected Components**: - Use Depth-First Search (DFS) to count the number of connected components. 3. **Intersection Calculation**: - Convert each list into a set and count the number of common elements between two sets. # Complexity - **Time Complexity**: - Constructing the adjacency list takes \(O(n^2), where \(n\) is the number of nodes, and \(m\) is the average size of each property list. - DFS traversal takes \(O(n + E)\), where \(E\) is the number of edges. - Overall complexity is approximately (O(n^2). - **Space Complexity**: - The adjacency list takes \(O(n^2)\) in the worst case. - The visited array takes \(O(n)\). - The set operations require \(O(m)\) space per function call. - Overall space complexity is approximately \(O(n^2 + m)\). # Code ```java class Solution { public int numberOfComponents(int[][] properties, int k) { int n=properties.length; List<List<Integer>> adj=new ArrayList(); for(int i=0;i<n;i++) adj.add(new ArrayList()); for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { if(possible(properties[i],properties[j],k)) { adj.get(i).add(j); adj.get(j).add(i); } } } boolean vis[]=new boolean[n+1]; int cnt=0; for(int i=0;i<n;i++) { if(!vis[i]) { dfs(i,vis,adj); cnt++; } } return cnt; } public static void dfs(int node,boolean vis[],List<List<Integer>> adj) { vis[node]=true; for(int it:adj.get(node)) { if(!vis[it]) dfs(it,vis,adj); } } public static boolean possible(int a[],int b[],int k) { Set<Integer> set1=new HashSet(); for(int ele:a) set1.add(ele); Set<Integer> set2=new HashSet(); for(int ele:b) { if(set1.contains(ele)) set2.add(ele); } return set2.size()>=k; } } ``` This solution efficiently constructs the graph and determines the number of connected components using DFS traversal.
3
0
['Java']
1
properties-graph
SIMPLE DFS APPROACH USING PYTHON
simple-dfs-approach-using-python-by-vish-33x4
Complexity Time complexity: O(n2) Space complexity: O(n) Code
VISHAAL-KUMAR
NORMAL
2025-03-23T04:18:43.726301+00:00
2025-03-23T04:18:43.726301+00:00
196
false
# Complexity - Time complexity: O(n2) - Space complexity: O(n) # Code ```python3 [] from collections import defaultdict class Solution: def numberOfComponents(self, properties: List[List[int]], k: int) -> int: n = len(properties) res = 1 visit = set() visit.add(0) graph = defaultdict(list) def intersect(a, b): return len(set(a) & set(b)) for i in range(n): for j in range(n): if intersect(properties[i], properties[j]) >= k and i != j: graph[i].append(j) graph[j].append(i) def dfs(index): for neighbour in graph[index]: if neighbour in visit: continue visit.add(neighbour) dfs(neighbour) dfs(0) for i in range(n): if i not in visit: dfs(i) res += 1 return res ```
3
0
['Python3']
1
properties-graph
simple c++ solution
simple-c-solution-by-22h51a66e5-7zg6
IntuitionApproachComplexity Time complexity: Worst-case O(nยฒ * m) Space complexity: O(n * m)Code
22h51a66e5
NORMAL
2025-03-23T04:06:17.352227+00:00
2025-03-23T04:06:17.352227+00:00
139
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> Worst-case O(nยฒ * m) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n * m) # Code ```cpp [] class Disjointset{ private: vector<int>par,rank; public: Disjointset(int n){ par.resize(n); rank.resize(n,0); for(int i=0;i<n;i++){ par[i]=i; } } int find(int x){ if(par[x]!=x){ par[x]=find(par[x]); } return par[x]; } void unite(int x,int y){ int rootx=find(x); int rooty=find(y); if(rootx!=rooty){ if(rank[rootx]>rank[rooty]){ par[rooty]=rootx; } else if(rank[rootx]<rank[rooty]){ par[rootx]=rooty; } else{ par[rooty]=rootx; rank[rootx]++; } } } bool isc(int x,int y){ return find(x)==find(y); } }; class Solution { public: int numberOfComponents(vector<vector<int>>& pro, int k) { vector<set<int>>vs(pro.size()); unordered_set<int>aa; Disjointset ds(pro.size()); for(int i=0;i<pro.size();i++){ for(auto j:pro[i]){ vs[i].insert(j); } } for(int i=0;i<pro.size();i++){ for(int l=i+1;l<pro.size();l++){ int cnt=0; for(auto j:vs[i]){ if(vs[l].find(j)!=vs[l].end()){ cnt++; if(cnt>=k){ds.unite(i,l);break;} } } } } for(int c=0;c<pro.size();c++){ aa.insert(ds.find(c)); } return aa.size(); } }; ```
3
0
['C++']
0
properties-graph
DSU based solution
dsu-based-solution-by-anubhavpathak03-u02a
I approched this solution by DSUI first solve these question to do this questionQuestion-1 (common element b/w two arrays)Question-2 (count the number of comple
anubhavpathak03
NORMAL
2025-03-24T10:42:13.148998+00:00
2025-03-24T10:42:13.148998+00:00
26
false
<!-- # Intuition --> <!-- Describe your first thoughts on how to solve this problem. --> <!-- # Approach --> <!-- Describe your approach to solving the problem. --> <!-- # Complexity --> <!-- - Time complexity: --> <!-- Add your time complexity here, e.g. $$O(n)$$ --> <!-- - Space complexity: --> <!-- Add your space complexity here, e.g. $$O(n)$$ --> ### I approched this solution by DSU ### I first solve these question to do this question [Question-1 (common element b/w two arrays)](https://leetcode.com/problems/find-common-elements-between-two-arrays/description/) [Question-2 (count the number of complete components)](https://leetcode.com/problems/count-the-number-of-complete-components/description/) #### Good Luck ๐Ÿ‘ # Code ```cpp [] class DisjointSet { public: vector<int> size, rank, parent; DisjointSet(int n) { size.resize(n+1, 1); rank.resize(n+1, 0); parent.resize(n+1); for(int i=0; i<=n; i++) parent[i] = i; } int findUltiParent(int n) { if(n == parent[n]) { return n; } return parent[n] = findUltiParent(parent[n]); } void unionByRank(int u, int v) { int root_u = findUltiParent(u); int root_v = findUltiParent(v); if(root_u == root_v) return; if(rank[root_u] < rank[root_v]) { parent[root_u] = root_v; } else if(rank[root_v] < rank[root_u]) { parent[root_v] = root_u; } else { parent[root_v] = root_u; rank[root_u]++; } } }; class Solution { public: bool intersect(unordered_set<int>& a, unordered_set<int>& b, int k) { int cnt = 0; for(auto it : a) { if(b.find(it) != b.end()) { cnt++; } } return cnt >= k; } int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); // SC->O(n*m) vector<unordered_set<int>> s(n); // TC->O(n*m) for(int i=0;i<n;i++){ for(auto &it : properties[i]) { s[i].insert(it); } } DisjointSet dsu(n); // TC-> O(n^2 * m) for(int i=0; i<n; i++) { for(int j=i+1; j<n; j++) { if(intersect(s[i], s[j], k)) { dsu.unionByRank(i, j); } } } // TC-> O(n * x(n)) x-> alpha int num_of_component = 0; for(int i=0; i<n; i++) { if(dsu.findUltiParent(i) == i) { num_of_component++; } } return num_of_component; } }; // TC -> O(n*m + n^2 * m + n*x(n)) // SC -> O(n*m) ```
2
0
['Union Find', 'C++']
0
properties-graph
Python3 || dfs || T/S: 84% / 99%
python3-dfs-ts-84-99-by-spaulding-9xwi
https://leetcode.com/problems/properties-graph/submissions/1583589292/I could be wrong, but I think that time complexity is *O(N ^2 * M) and space complexity is
Spaulding_
NORMAL
2025-03-23T18:44:10.916932+00:00
2025-03-23T18:44:10.916932+00:00
14
false
```python3 [] class Solution: def numberOfComponents(self, properties: List[List[int]], k: int) -> int: def areConnected(list1, list2): return len(set(list1) & set(list2)) >= k def dfs(node: int) -> None: stack = [node] while stack: node = stack.pop() for nei in range(n): if nei not in unseen: continue if areConnected(properties[node], properties[nei]): unseen.remove(nei) stack.append(nei) return n, ans = len(properties), 0 unseen = set(range(n)) while unseen: ans += 1 node = unseen.pop() dfs(node) return ans ``` [https://leetcode.com/problems/properties-graph/submissions/1583589292/](https://leetcode.com/problems/properties-graph/submissions/1583589292/) I could be wrong, but I think that time complexity is **O*(*N* ^2 * *M*) and space complexity is *O*(*N* + *M*), in which *N* ~ `len(nums)`. and *M* ~ maximum length of lists in `g.values()`
2
0
['Python3']
0
properties-graph
๐Ÿ—๏ธ Counting Connected Components in a Graph ๐Ÿ—๏ธ
counting-connected-components-in-a-graph-2muy
๐Ÿ’ก Intuition:We need to determine how many connected components exist in a graph constructed from the given properties array.Each index in properties represents
opWzPXRgDd
NORMAL
2025-03-23T04:29:57.000931+00:00
2025-03-23T04:29:57.000931+00:00
97
false
# ๐Ÿ’ก Intuition: <!-- Describe your first thoughts on how to solve this problem. --> We need to determine how many connected components exist in a graph constructed from the given `properties` array. Each index in `properties` represents a node, and an edge is formed between two nodes if they share at least `k` common distinct integers. The number of connected components in the graph represents our answer. # ๐Ÿ› ๏ธ Approach: <!-- Describe your approach to solving the problem. --> 1. Build the Graph: - Convert each `properties[i]` list into a set for easy intersection calculations. - Create an adjacency list where two nodes are connected if they share at least `k` common numbers. 2. Perform DFS Traversal: - Maintain a `visited` list to track explored nodes. - Use DFS to traverse all connected nodes, marking them as visited. - Each new DFS call represents discovering a new connected component. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> Constructing the adjacency list takes $$O(n^2 * m)$$ in the worst case (checking all pairs). DFS traversal takes $$O(n + e)$$, where e is the number of edges. Overall, it remains $$O(n^2 * m)$$ in the worst case. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(n^2)$$ for adjacency list in the worst case. $$O(n)$$ for visited array and recursion stack. Overall: $$O(n^2)$$ worst-case space usage. # Code ```python3 [] class Solution: def numberOfComponents(self, properties: List[List[int]], k: int) -> int: n = len(properties) def intersect(a, b): seta = set(a) setb = set(b) return len(seta.intersection(setb)) adj = [[] for _ in range(n)] # Adjacency list to represent the graph # Build the graph for i in range(n): for j in range(i + 1, n): if intersect(properties[i], properties[j]) >= k: adj[i].append(j) adj[j].append(i) # Graph is undirected visited = [False] * n count = 0 def dfs(node): visited[node] = True for neighbor in adj[node]: if not visited[neighbor]: dfs(neighbor) # Count connected components for i in range(n): if not visited[i]: dfs(i) count += 1 return count ``` ![DALLยทE 2025-03-23 09.58.58 - A fun and engaging poster asking for upvotes on a LeetCode solution. The poster features a graph with connected components highlighted in different co.webp](https://assets.leetcode.com/users/images/f7098d00-272a-4023-8f53-5232fddac2ba_1742704147.0155377.webp)
2
0
['Array', 'Depth-First Search', 'Graph', 'Python3']
0
properties-graph
Python | Union Find
python-union-find-by-prince0018-ej6h
Code
prince0018
NORMAL
2025-03-23T04:06:50.855968+00:00
2025-03-23T04:06:50.855968+00:00
49
false
# Code ```python3 [] class Solution: def numberOfComponents(self, properties: List[List[int]], k: int) -> int: edges=[] for x in range(len(properties)-1): for y in range(x+1,len(properties)): hash1=set(Counter(properties[x]).keys()) hash2=set(Counter(properties[y]).keys()) if len(hash1.intersection(hash2))>=k: edges.append((x,y)) par=[x for x in range(len(properties))] rank=[1]*len(properties) def find(n1): res=n1 while res!=par[res]: par[res]=par[par[res]] res=par[res] return res def union(n1,n2): p1,p2=find(n1),find(n2) if p1==p2: return 0 if rank[p1]>rank[p2]: rank[p1]+=rank[p2] par[p2]=p1 else: rank[p2]+=rank[p1] par[p1]=p2 return 1 res=len(properties) for n1,n2 in edges: res-=union(n1,n2) return res ```
2
0
['Union Find', 'Python3']
1
properties-graph
โœ… โŸฃ Java Solution โŸข
java-solution-by-harsh__005-hil7
Code
Harsh__005
NORMAL
2025-03-23T04:02:08.899679+00:00
2025-03-23T04:02:08.899679+00:00
78
false
# Code ```java [] class Solution { private void dfs(boolean[] used, Map<Integer, List<Integer>> map, int v) { used[v] = true; for(int child : map.getOrDefault(v, new ArrayList<>())) { if(!used[child]) { dfs(used, map, child); } } } public int numberOfComponents(int[][] properties, int K) { Map<Integer, List<Integer>> map = new HashMap<>(); int n = properties.length, m = properties[0].length; for(int i=0; i<n; i++) { for(int j=i+1; j<n; j++) { int[][] ct = new int[101][2]; Set<Integer> set = new HashSet<>(); for(int k=0; k<m; k++) { int v1 = properties[i][k], v2 = properties[j][k]; if(ct[v1][0] == 0) ct[v1][0]++; if(ct[v2][1] == 0) ct[v2][1]++; if(ct[v1][0]==1 && ct[v1][1]==1) set.add(v1); if(ct[v2][0]==1 && ct[v2][1]==1) set.add(v2); } if(set.size() >= K) { map.putIfAbsent(i, new ArrayList<>()); map.putIfAbsent(j, new ArrayList<>()); map.get(i).add(j); map.get(j).add(i); } } } boolean used[] = new boolean[n]; int ans = 0; for(int i=0; i<n; i++) { if(!used[i]) { ans++; dfs(used, map, i); } } return ans; } } ```
2
0
['Java']
1
properties-graph
Easy cpp and Javaโœ…
easy-cpp-and-java-by-pune18-ti65
IntuitionThe problem involves finding the number of connected components in a graph where nodes represent arrays, and edges exist between nodes if they share at
pune18
NORMAL
2025-03-23T04:02:04.598888+00:00
2025-03-24T01:46:05.568886+00:00
129
false
# Intuition The problem involves finding the number of connected components in a graph where nodes represent arrays, and edges exist between nodes if they share at least k distinct common integers. The key insight is to model this as a graph problem and use Depth-First Search (DFS) to count the connected components. # Approach 1. Graph Construction: * Each array is treated as a node in the graph. * An edge is added between two nodes if the number of distinct common integers between their corresponding arrays is at least k. 2. Intersection Calculation: * A helper function intersect calculates the number of distinct common integers between two arrays using sets. 3. DFS Traversal: * DFS is used to traverse the graph and mark all reachable nodes from a starting node, effectively identifying a connected component. * The process is repeated for all unvisited nodes to count the total number of connected components. # Complexity - Time complexity: O(n^2โ‹…m+n+e) - Space complexity: O(nโ‹…m+n+e) # Code ```java [] import java.util.*; class Solution { // Helper function to calculate the number of distinct common integers between two arrays private int intersect(int[] a, int[] b) { Set<Integer> setA = new HashSet<>(); for (int num : a) setA.add(num); Set<Integer> setB = new HashSet<>(); for (int num : b) setB.add(num); setA.retainAll(setB); // Retain only common elements return setA.size(); } // DFS to traverse the graph and mark visited nodes private void dfs(int node, Map<Integer, List<Integer>> graph, Set<Integer> visited) { visited.add(node); for (int neighbor : graph.getOrDefault(node, new ArrayList<>())) { if (!visited.contains(neighbor)) { dfs(neighbor, graph, visited); } } } public int numberOfComponents(int[][] properties, int k) { int n = properties.length; // Build the graph Map<Integer, List<Integer>> graph = new HashMap<>(); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (intersect(properties[i], properties[j]) >= k) { // Add edge between i and j graph.computeIfAbsent(i, x -> new ArrayList<>()).add(j); graph.computeIfAbsent(j, x -> new ArrayList<>()).add(i); } } } // Count connected components using DFS Set<Integer> visited = new HashSet<>(); int components = 0; for (int i = 0; i < n; i++) { if (!visited.contains(i)) { dfs(i, graph, visited); components++; } } return components; } } ``` ```c++ [] class Solution { public: vector<vector<int>> build_graph(const vector<vector<int>>& p, int k) { int n = p.size(); vector<vector<int>> adj_list(n); vector<unordered_set<int>> s(n); // Convert properties to sets for fast lookup for (int i = 0; i < n; i++) { for (auto &x: p[i]) s[i].insert(x); } // Check all pairs of nodes for at least k common properties for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int common = 0; for (auto &x: s[j]) { if (s[i].count(x)) common++; if (common >= k) break; } if (common >= k) { adj_list[i].push_back(j); adj_list[j].push_back(i); } } } return adj_list; } void dfs(int node, const vector<vector<int>>& adj_list, vector<bool>& visited) { visited[node] = true; for (int neigh: adj_list[node]) { if (!visited[neigh]) { dfs(neigh, adj_list, visited); } } } int numberOfComponents(vector<vector<int>>& properties, int k) { vector<vector<int>> adj = build_graph(properties, k); int n = properties.size(); vector<bool> visited(n, false); int count = 0; for (int i = 0; i < n; i++) { if (!visited[i]) { count++; dfs(i, adj, visited); } } return count; } }; ```
2
1
['Ordered Map', 'Ordered Set', 'C++', 'Java']
1
properties-graph
C, Union-Find 100%
c-union-find-100-by-nikamir-955r
IntuitionUse union-find, use the bit masks to store the propertiesComplexity Time complexity: O(n2) Space complexity: O(n) Code
nikamir
NORMAL
2025-03-31T20:12:04.219258+00:00
2025-03-31T20:38:30.159501+00:00
9
false
# Intuition Use union-find, use the bit masks to store the properties # Complexity - Time complexity: $$O(n^2)$$ - Space complexity: $$O(n)$$ # Code ```c [] /* hold bits for ~100 properties 2x64 bit numbers*/ typedef struct { /* tree of sets, set size, link to parent */ unsigned char size, parent; unsigned long long props[2]; } setData; /* union find instance */ typedef struct { unsigned char nSets; /* numbers of disjoint sets*/ setData* data; /* Data for each set member */ } unionFind; /* efficient bit count for 64 bit numbers */ unsigned char bitCount(unsigned long data) { data = (data & 0x5555555555555555) + ((data & 0xAAAAAAAAAAAAAAAA) >> 1); data = (data & 0x3333333333333333) + ((data & 0xCCCCCCCCCCCCCCCC) >> 2); data = (data & 0x0F0F0F0F0F0F0F0F) + ((data & 0xF0F0F0F0F0F0F0F0) >> 4); data = (data & 0x00FF00FF00FF00FF) + ((data & 0xFF00FF00FF00FF00) >> 8); data = (data & 0x0000FFFF0000FFFF) + ((data & 0xFFFF0000FFFF0000) >> 16); data = (data & 0x00000000FFFFFFFF) + ((data & 0xFFFFFFFF00000000) >> 32); return data; } /* finding the set by its member, returnse the set id */ unsigned char getSet(unionFind* pufData, unsigned char x) { unsigned char curX = x; unsigned char prevX = pufData->data[curX].parent; /* traverse to the parent */ while (prevX != curX) { curX = prevX; prevX = pufData->data[curX].parent; } /* walk again to compress the path */ curX = pufData->data[x].parent; while (curX != prevX) { pufData->data[x].parent = prevX; x = curX; curX = pufData->data[x].parent; } return prevX; } /* join two sets, returns 1 if the join took place or 0 x and y are already in the same set */ unsigned char unionSets(unionFind* pufData, unsigned char x, unsigned char y) { x = getSet(pufData, x); y = getSet(pufData, y); if (x == y) return 0; /* merge smaller to larger */ if (pufData->data[x].size >= pufData->data[y].size) { pufData->data[x].size += pufData->data[y].size; pufData->data[y].parent = x; } else { pufData->data[y].size += pufData->data[x].size; pufData->data[x].parent = y; } /* reduce the current number of sets*/ --pufData->nSets; return 1; } /* Allocate to "size" sets */ void allocateUFData(unionFind* puf, int size) { puf->nSets = size; puf->data = malloc(size * sizeof(setData)); } /* deallocate tje UF structure */ void deallocateUFData(unionFind* puf) { free(puf->data); } int numberOfComponents(int** properties, int propertiesSize, int* propertiesColSize, int k) { unionFind ufData; allocateUFData(&ufData, propertiesSize); /* Populate the UF structure */ setData* tempData = ufData.data; int** curProperties = properties; int* curPropColSize = propertiesColSize; unsigned char x, y; for (x = 0; x < propertiesSize; ++x, ++tempData, ++curProperties, ++curPropColSize) { /* each set is size 1 at start*/ tempData->size = 1; /* properties set to 0 */ tempData->props[0] = 0UL; tempData->props[1] = 0UL; tempData->parent = x; /* each set is unique at start 0..n-1 */ /* Collect properties into bits */ int* curProperty = *curProperties; for (y = 0; y < *curPropColSize; ++y, ++curProperty) { /* under 64 to lower part, over 64 to higher part */ if (*curProperty < 64) { tempData->props[0] |= (1UL << *curProperty); } else { tempData->props[1] |= (1UL << (*curProperty - 64)); } } } /* run the edge check between every pair or the vertices: x,y */ setData* xData = ufData.data + 1; for (x = 1; x < propertiesSize; ++x, ++xData) { setData* yData = ufData.data; for (y = 0; y < x; ++y, ++yData) { unsigned char flagCount = bitCount(xData->props[0] & yData->props[0]); if (flagCount >= k || (flagCount + bitCount(xData->props[1] & yData->props[1])) >= k) { if (unionSets(&ufData, x, y) == 1) { if (ufData.nSets == 1) { /* if already down to 1 set, stop and return 1 */ deallocateUFData(&ufData); return 1; } } } } } deallocateUFData(&ufData); return ufData.nSets; } ```
1
0
['C']
0
properties-graph
Beginner Friendly Adjacency List + DFS using unordered sets | C++ | Beats 100%
beginner-friendly-adjacency-list-dfs-usi-ng3v
IntuitionEach row is converted to a set to eliminate duplicates. For all pairs of rows, edges are added if their intersection size meets k. Finally, DFS travers
pratiiik_p
NORMAL
2025-03-28T10:03:33.085818+00:00
2025-03-28T10:03:33.085818+00:00
17
false
# Intuition Each row is converted to a set to eliminate duplicates. For all pairs of rows, edges are added if their intersection size meets `k`. Finally, DFS traverses the graph to count connected components. # Approach 1. **Preprocessing Rows into Sets:** - Convert each row into an `unordered_set` to eliminate duplicate elements within the same row. This ensures that the intersection count between rows is based on distinct values. 2. **Building the Graph:** - For each pair of rows (i, j) where `i < j`, compute the intersection size of their sets using a helper function. - If the intersection size is โ‰ฅ `k`, add an undirected edge between nodes `i` and `j` in an adjacency list (`H`). 3. **DFS for Connected Components:** - Initialize a `visited` array to track nodes traversed. - For each unvisited node, perform DFS to mark all reachable nodes as visited. Each DFS initiation corresponds to a new connected component. **Example Walkthrough (k=1):** - **Rows Converted to Sets:** ``` {1,2}, {1}, {3,4}, {4,5}, {5,6}, {7} ``` - **Edges Created:** - (0-1), (2-3), (3-4) (each pair shares โ‰ฅ1 element). - **Connected Components:** - Component 1: Nodes 0, 1 (connected via shared '1'). - Component 2: Nodes 2, 3, 4 (connected via 2-3 and 3-4). - Component 3: Node 5 (no edges). **Result:** 3 components. # Complexity - Time complexity: $$O(nยฒ * m)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> where `n` is the number of rows and `m` is the average row size. - Space complexity: $$O(nยฒ + n*m)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> storing adjacency lists for up to O(nยฒ) edges and O(n*m) for row sets. # Code ```cpp [] class Solution { public: int intersect(unordered_set <int> &a, unordered_set <int> &b){ int count = 0; for(auto &n: b){ if(a.find(n)!=a.end())count++; } return count; } void dfs(int i, vector <bool> &visited, unordered_map <int, vector <int>> &H){ visited[i] = true; for(auto &node: H[i]){ if(!visited[node])dfs(node, visited, H); } } int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); unordered_map <int, vector <int>> H; // Adjacency list for graph vector <bool> visited(n, false); // Tracks visited nodes vector <unordered_set <int>> p; // Stores each row as a set // Convert each row to a set to remove duplicates (also reduces time complexity) for(auto u: properties){ unordered_set <int> temp(u.begin(), u.end()); p.push_back(temp); } // Build graph for(int i=0; i<n; i++){ for(int j=i+1; j<n; j++){ if((intersect(p[i], p[j])>=k)){ H[i].push_back(j); H[j].push_back(i); } } } int res = 0; for(int i=0; i<n; i++){ if(!visited[i]){ res++; dfs(i, visited, H); } } return res; } }; ```
1
0
['Hash Table', 'Depth-First Search', 'Ordered Set', 'C++']
0
properties-graph
Beginners Friendly ! Easy to Understand
beginners-friendly-easy-to-understand-by-2fwt
IntuitionApproachComplexity Time complexity: O(n*m) Space complexity: O(n*m) Code
jayprakash00012
NORMAL
2025-03-28T06:44:53.901166+00:00
2025-03-28T06:44:53.901166+00:00
14
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n*m) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n*m) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int intersect(vector<int> &a,vector<int> &b){ unordered_set<int> st(a.begin(),a.end()); sort(b.begin(),b.end()); int ans=0; for(int i=0;i<b.size();i++){ if(i>0){ if(b[i]==b[i-1]) continue; } if(st.find(b[i])!=st.end()){ ans++; } } return ans; } void dfs(unordered_map<int,vector<int>> &adj,int u,vector<int> &visited){ visited[u]=1; for(auto it:adj[u]){ if(visited[it]==-1){ dfs(adj,it,visited); } } } int numberOfComponents(vector<vector<int>>& properties, int k) { int n= properties.size(); unordered_map<int,vector<int>> adj; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(intersect(properties[i],properties[j])>=k){ adj[i].push_back(j); adj[j].push_back(i); } } } vector<int> visited(n,-1); int ans=0; for(int i=0;i<n;i++){ if(visited[i]==-1){ dfs(adj,i,visited); ans++; } } return ans; } }; ```
1
0
['Array', 'Hash Table', 'Depth-First Search', 'Graph', 'C++']
0
properties-graph
Disjoint Set & Set intersection - Python solution
disjoint-set-set-intersection-python-sol-m0ed
Intuition & ApproachThis problem can be divited (and the conquered) into two smaller problems.IntersectionWe need an efficient way to find number of distinct in
agayev169
NORMAL
2025-03-26T13:46:04.693892+00:00
2025-03-26T13:47:02.415755+00:00
14
false
# Intuition & Approach This problem can be divited (and the conquered) into two smaller problems. ## Intersection We need an efficient way to find number of distinct integers common to two arrays. The most efficient way to do this is to pre-convert all the arrays to sets and then do an intersection operation between sets. An intersection of two sets usually takes $$O(N)$$ time since it takes $$O(1)$$ time to find whether a value is presented in a set, therefore, for $$N$$ values it will take $$O(N)$$ time. ## Relationship between nodes We need an efficient way to find relationship between nodes of our graph (each node is represented by an array as descibed in the problem description). This problem is usually solved by Disjoint Set/Find-Union data structure (you may check out [explore card for disjoint set](https://leetcode.com/explore/learn/card/graph/618/disjoint-set/) for more details). The data structure (sometimes recalled as algorithm) is fairly simple. You have two methods: `find(node)` and `union(node1, node2)`. `find(node)` method finds the root of a graph that `node` is a part of. `union(node1, node2)` on the other hand unions two graphs into a bigger graph. To do this efficiently, we create a list of `parents` which is first filled with `-1`s representing that each node is its parent. Since we haven't started the creation of the relations yet, this is a correct representation of our graph. For each two connected nodes in our graph, we union them by setting `parents[node2] = node1`. After processing all the nodes we have our `parents` list with the parent node set for each node we have. The number of remaining ``-1``s in the `parents` list is the number of connected components. # Complexity - Time complexity: $$O(n^2m)$$, where $$n$$ is the number of nodes (length of `properties` list), and $$m$$ is the number of elements in each property. ## Explanation We have two nested loops to intersect each two nodes, this is $$O(n^2)$$. Then intersection operation takes $$O(m)$$ time and union operation takes $$O(1)$$ time. Therefore, the final time complexity is $$O(n^2m)$$. - Space complexity: $$O(nm)$$, where $$n$$ is the number of nodes (length of `properties` list), and $$m$$ is the number of elements in each property. ## Explanation We need to pre-convert all the given properties lists to sets, which use $$O(nm)$$ space. We also use $$O(n)$$ space for `parents` list. Therefore, the final space complexity is $$O(nm)$$. # Code ```python3 [] class Solution: def intersect(self, a: set[int], b: set[int]) -> int: return len(a.intersection(b)) def find(self, n: int) -> int: if self.parents[n] == -1: return n self.parents[n] = self.find(self.parents[n]) return self.parents[n] def union(self, n1: int, n2: int) -> None: r1 = self.find(n1) r2 = self.find(n2) if r1 == r2: return self.parents[r2] = r1 def numberOfComponents(self, properties: List[List[int]], k: int) -> int: n = len(properties) numSet = [set(p) for p in properties] self.parents = [-1 for _ in range(n)] for i in range(n-1): for j in range(i+1, n): if self.intersect(numSet[i], numSet[j]) >= k: self.union(i, j) res = 0 for p in self.parents: if p == -1: res += 1 return res ``` ![image.png](https://assets.leetcode.com/users/images/5e296fb9-bdd5-4c76-8867-7d5f34a8b2d9_1742996700.555299.png)
1
0
['Hash Table', 'Union Find', 'Graph', 'Python3']
1
properties-graph
Simple and easy to understand | BFS | Python3 | Beats 80%
simple-and-easy-to-understand-bfs-python-pogq
Please UpvoteCode
Alpha2404
NORMAL
2025-03-26T02:16:48.559953+00:00
2025-03-26T02:16:48.559953+00:00
11
false
# Please Upvote # Code ```python3 [] class Solution: def numberOfComponents(self, properties: List[List[int]], k: int) -> int: n = len(properties) m = len(properties[0]) def intersect(a, b): return len(set(a).intersection(set(b))) adj = defaultdict(list) for i in range(n): for j in range(n): if i==j: continue else: if intersect(properties[i],properties[j])>=k: adj[i].append(j) visited = set() count = 0 def bfs(node): qu = deque() qu.append(node) visited.add(node) while qu: temp = qu.popleft() for nei in adj[temp]: if nei not in visited: qu.append(nei) visited.add(nei) return for i in range(n): if i not in visited: count+=1 bfs(i) return count ```
1
0
['Array', 'Hash Table', 'Breadth-First Search', 'Graph', 'Python3']
0
properties-graph
Simple || DFS || Beginner Friendly || Counting โœ…๐ŸŽฏ
simple-dfs-beginner-friendly-counting-by-6lzt
Approach:dfs(u, vis, adj): Standard depth-first search (DFS) to traverse connected components in an adjacency list representation of a graph. Marks visited node
mayankn31
NORMAL
2025-03-24T19:14:48.065845+00:00
2025-03-24T19:14:48.065845+00:00
20
false
# Approach: ## dfs(u, vis, adj): - Standard depth-first search (DFS) to traverse connected components in an adjacency list representation of a graph. - Marks visited nodes to avoid reprocessing. ## intersect(a, b): - Uses two binary arrays (one and two) of size 101 to track the presence of numbers in arrays a and b. - Checks how many indices have 1 in both arrays (i.e., common distinct integers). ## numberOfComponents(properties, k) - Graph Construction: Creates an adjacency list where edges are added if two properties share at least k common elements. - Connected Component Counting: Uses DFS to count the number of connected components in the graph. # Code ```cpp [] class Solution { public: void dfs(int u,vector<bool>& vis,unordered_map<int,vector<int>>& adj){ vis[u]=true; for(int &v:adj[u]){ if(!vis[v]) dfs(v,vis,adj); } } int intersect(vector<int>& a,vector<int>& b){ int cnt=0; vector<int>one(100+1,0); vector<int>two(100+1,0); for(int &x:a) one[x]=1; for(int &x:b) two[x]=1; for(int i=1;i<=100;i++) cnt+=one[i]&two[i]; return cnt; } int numberOfComponents(vector<vector<int>>& properties, int k) { unordered_map<int,vector<int>> adj; int n=properties.size(); for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(intersect(properties[i], properties[j])>=k){ adj[i].push_back(j); adj[j].push_back(i); } } } int res=0; vector<bool>vis(n,false); for(int i=0;i<n;i++){ if(!vis[i]){ dfs(i,vis,adj); res++; } } return res; } }; ```
1
0
['Array', 'Hash Table', 'Depth-First Search', 'Graph', 'Counting', 'C++']
0
properties-graph
๐Ÿ˜€100% User Beat | ๐Ÿ’ก DFS | Java
100-user-beat-dfs-java-by-s_a_m2003-cg3f
IntuitionApproachComplexity Time complexity: Space complexity: Code
s_a_m2003
NORMAL
2025-03-24T10:56:50.666949+00:00
2025-03-24T10:56:50.666949+00:00
13
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { Map<Integer,List<Integer>> graph = new HashMap<>(); public int numberOfComponents(int[][] properties, int k) { int v = properties.length; for(int i = 0 ; i < v; i++){ graph.put(i,new ArrayList<>()); } for(int i = 0 ; i < v; i++){ for(int j = 0; j < v; j++){ if(i != j && checkIntersection(properties[i],properties[j],k)){ addEdge(graph,i,j); } } } int cc = connectedComponent(graph, v); System.out.println(cc); return cc; } public boolean checkIntersection(int arr1[], int arr2[], int k){ Arrays.sort(arr1); Arrays.sort(arr2); int i = 0; int j = 0; Set<Integer> set = new HashSet<>(); while(i < arr1.length && j < arr2.length){ if(arr1[i] == arr2[j]){ set.add(arr1[i]); i++; j++; } else if(arr1[i] > arr2[j]){ j++; }else{ i++; } } if(set.size() >= k){ return true; } return false; } public void addEdge(Map<Integer,List<Integer>> graph, int v1, int v2){ graph.get(v1).add(v2); graph.get(v2).add(v1); } public int connectedComponent(Map<Integer,List<Integer>> graph,int v) { // one thing that you know Graph is disconnected(Some of them are connected) // to go on each starting node you have to create an array of visited array int visited[] = new int[v]; // after that i will try to find all possible diconnected component via // using visited array... int count = 0; for(int i = 0; i < visited.length; i++){ if(visited[i] == 0){ count++; dfs(graph,visited,i); } } return count; } public void dfs(Map<Integer,List<Integer>> graph, int []visited,int src){ Stack<Integer> stack = new Stack<>(); stack.push(src); while(!stack.isEmpty()){ int v = stack.pop(); if(visited[v] == 1){ continue; } visited[v] = 1; for(int nbrs : graph.get(v)){ if(visited[nbrs] != 1){ stack.push(nbrs); } } } } } ```
1
0
['Depth-First Search', 'Graph', 'Java']
0
properties-graph
simple intuitive approach .beats 78 perc . o(n2) .
simple-intuitive-approach-beats-78-perc-rbcun
Approachfirst we will sort all the arrays in properties and remove their duplicates. then we will take 2 arrays and check if their intersection ( ie common uniq
alokth1302
NORMAL
2025-03-24T01:49:21.091032+00:00
2025-03-24T01:49:21.091032+00:00
9
false
# Approach first we will sort all the arrays in properties and remove their duplicates. then we will take 2 arrays and check if their intersection ( ie common unique elements) is greater than k. to do this we have used a 2 pointers approach. if intersection comes out to be greater than k .we form an undirected edge between node i and node j. for this we are maintaining an adjacency list g. then we apply dfs. we traverse over all nodes.if it is unvisited we visit that node and all its neighbours and their neighbours...recursively and color them with their component no. in the end we return no of components. # Complexity - Time complexity: o(n2) # Code ```cpp [] class Solution { public: int intersect(vector<int>a,vector<int>b) { int i=0,j=0; int ct=0; while(i<a.size() && j<b.size()){ if(a[i]==b[j]) { ct++; i++; j++; } else if(a[i]<b[j]) { i++; } else j++; } // cout<<ct; return ct; } void dfs(vector<vector<int>>&g,int i,int compno,vector<int>&vis) { vis[i]=compno; for(auto u:g[i]) { if(vis[u]==0) { dfs(g,u,compno,vis); } } } int numberOfComponents(vector<vector<int>>& properties, int k) { vector<vector<int>>g; int n=properties.size(); g.resize(n); for(int i=0;i<n;i++) { sort(properties[i].begin(),properties[i].end()); properties[i].erase(unique(properties[i].begin(),properties[i].end()),properties[i].end()); //for(auto u: properties[i]) //cout<<u<<" "; cout<<endl; } for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { int ic=(intersect(properties[i],properties[j])); if(ic>=k) { // cout<<"between "<<i<<"and "<<j<<" intersection : "<<k<<endl; g[i].push_back(j); g[j].push_back(i); } } } vector<int>vis(n,0); int compno=0; for(int i=0;i<n;i++) { if(vis[i]==0) { compno++; dfs(g,i,compno,vis); } } return compno; } }; ```
1
0
['C++']
0
properties-graph
DSU/UnionFind. 450ms
dsuunionfind-by-vokasik-y86x
Code
vokasik
NORMAL
2025-03-23T23:49:41.342978+00:00
2025-03-23T23:50:24.465864+00:00
11
false
# Code ```python3 class Solution: def numberOfComponents(self, grid: List[List[int]], k: int) -> int: def union(a,b): nonlocal components if (roota := find(a)) != (rootb := find(b)): if sizes[roota] > sizes[rootb]: parents[rootb] = roota sizes[roota] += sizes[rootb] else: parents[roota] = rootb sizes[rootb] += sizes[roota] components -= 1 def find(e): if parents[e] != e: parents[e] = (e := find(parents[e])) return e components = N = len(grid) sizes = {i:1 for i in range(N)} parents = {i:i for i in range(N)} for i in range(N): for j in range(i + 1, N): if len(set(grid[i]) & set(grid[j])) >= k: union(i, j) return components ```
1
0
['Union Find', 'Python3']
0
properties-graph
Optimal DFS Solution in C++, JAVA & PYTHON
optimal-dfs-solution-in-c-java-python-by-ofdg
Understanding Connected Components in Graphs: A Multi-Language ApproachIntroductionConnected components are a fundamental concept in graph theory, often used in
dipesh1203
NORMAL
2025-03-23T20:15:25.869284+00:00
2025-03-23T20:15:25.869284+00:00
26
false
# Understanding Connected Components in Graphs: A Multi-Language Approach ## Introduction Connected components are a fundamental concept in graph theory, often used in clustering problems, social network analysis, and recommendation systems. In this blog, we will explore an efficient approach to solving a problem involving connected components using DFS (Depth First Search). We'll implement the solution in **C++, Java, and Python**. ## Problem Statement Given a list of properties represented as an adjacency matrix, we need to determine the number of connected components based on a similarity threshold **k**. Two nodes (properties) are considered connected if they share at least **k** common attributes. ## Approach 1. **Graph Construction:** Treat properties as nodes and create an edge between two nodes if they share **k** or more attributes. 2. **DFS Traversal:** Use DFS to explore connected nodes and count the number of connected components. 3. **Set Intersection:** Determine common elements between two properties efficiently using a HashSet. --- ## **Java Implementation** ```java import java.util.*; class Solution { class Edge { int src, dest; public Edge(int src, int dest) { this.src = src; this.dest = dest; } } public int intersection(int[][] properties, int i, int j) { Set<Integer> set = new HashSet<>(); Set<Integer> setj = new HashSet<>(); for (int k : properties[j]) setj.add(k); for (int k : properties[i]) { if (setj.contains(k)) set.add(k); } return set.size(); } public void dfs(ArrayList<Edge>[] graph, int src, boolean[] visited) { visited[src] = true; for (Edge e : graph[src]) { if (!visited[e.dest]) { dfs(graph, e.dest, visited); } } } public int numberOfComponents(int[][] properties, int k) { int v = properties.length; ArrayList<Edge>[] graph = new ArrayList[v]; for (int i = 0; i < v; i++) graph[i] = new ArrayList<>(); for (int i = 0; i < v; i++) { for (int j = i + 1; j < v; j++) { if (intersection(properties, i, j) >= k) { graph[i].add(new Edge(i, j)); graph[j].add(new Edge(j, i)); } } } int count = 0; boolean[] visited = new boolean[v]; for (int i = 0; i < v; i++) { if (!visited[i]) { count++; dfs(graph, i, visited); } } return count; } } ``` --- ## **C++ Implementation** ```cpp #include <bits/stdc++.h> using namespace std; class Solution { public: int intersection(vector<vector<int>>& properties, int i, int j) { unordered_set<int> setj(properties[j].begin(), properties[j].end()); int count = 0; for (int num : properties[i]) { if (setj.count(num)) count++; } return count; } void dfs(vector<vector<int>>& graph, vector<bool>& visited, int node) { visited[node] = true; for (int neighbor : graph[node]) { if (!visited[neighbor]) { dfs(graph, visited, neighbor); } } } int numberOfComponents(vector<vector<int>>& properties, int k) { int v = properties.size(); vector<vector<int>> graph(v); for (int i = 0; i < v; i++) { for (int j = i + 1; j < v; j++) { if (intersection(properties, i, j) >= k) { graph[i].push_back(j); graph[j].push_back(i); } } } int count = 0; vector<bool> visited(v, false); for (int i = 0; i < v; i++) { if (!visited[i]) { count++; dfs(graph, visited, i); } } return count; } }; ``` --- ## **Python Implementation** ```python def intersection(properties, i, j): setj = set(properties[j]) return len([x for x in properties[i] if x in setj]) def dfs(graph, src, visited): visited[src] = True for neighbor in graph[src]: if not visited[neighbor]: dfs(graph, neighbor, visited) def number_of_components(properties, k): v = len(properties) graph = [[] for _ in range(v)] for i in range(v): for j in range(i + 1, v): if intersection(properties, i, j) >= k: graph[i].append(j) graph[j].append(i) count = 0 visited = [False] * v for i in range(v): if not visited[i]: count += 1 dfs(graph, i, visited) return count ``` --- ## **Time Complexity Analysis** - **Graph Construction:** O(Nยฒ ร— M), where N is the number of nodes and M is the average length of each property list. - **DFS Traversal:** O(N + E), where E is the number of edges. - **Total Complexity:** Approximately **O(Nยฒ ร— M)**. ## **Conclusion** In this blog, we discussed how to find connected components using DFS across multiple programming languages. The key takeaways are: - Efficient **set operations** to determine common attributes. - **DFS traversal** to count connected components. - **Graph adjacency list representation** to store connections efficiently. This approach is useful in **clustering, recommendation systems, and social network analysis**. ๐Ÿš€ Happy Coding!
1
0
['Depth-First Search', 'Graph', 'Ordered Set', 'Python', 'C++', 'Java', 'Python3']
0
properties-graph
Easy solution using Map and Set
easy-solution-using-map-and-set-by-abh15-v16f
Approach Use a map array to store the connected node. Check every possible pair. For each pair i,j: If 2 nodes i&j are connected, store the smallest of ther
Abh15hek
NORMAL
2025-03-23T20:10:41.271137+00:00
2025-03-23T20:10:41.271137+00:00
8
false
# Approach <!-- Describe your approach to solving the problem. --> - Use a map array to store the connected node. - Check every possible pair. For each pair i,j: - If 2 nodes i&j are connected, store the smallest of there map values in both map[i] and map[j]. - Add the minimum value of the connected nodes in set - return the size of set # Code ```java [] class Solution { public int numberOfComponents(int[][] p, int k) { Set<Integer> set=new HashSet<>(); int map[]=new int[p.length]; for(int i=0;i<p.length;i++) map[i]=i; for(int i=0;i<p.length;i++){ for(int j=0;j<p.length;j++){ if(i==j) continue; if(check(p[i],p[j],k)){ int x=Math.min(map[i],map[j]); map[i]=x; map[j]=x; } } } for(int i=0;i<p.length;i++){ int x=i; while(map[x]!=x) x=map[x]; set.add(x); } return set.size(); } boolean check(int[] a, int[] b, int k){ Set<Integer> set=new HashSet<>(); for(int it:a) set.add(it); for(int it:b) if(set.contains(it)){ k--; set.remove(it); } return k<=0; } } ```
1
0
['Java']
0
properties-graph
C++ || Simple and Easy Explanation || Union-Find
c-simple-and-easy-explanation-union-find-ayln
IntuitionApproachComplexity Time complexity: Space complexity: Code
jhanvi_sankhla
NORMAL
2025-03-23T17:27:40.079544+00:00
2025-03-23T17:27:40.079544+00:00
8
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> We need to find connected components, The most intitutive approach for that is Union Set. # Approach <!-- Describe your approach to solving the problem. --> 1.Write a function for intersect using two pointer. For that we need to sort the vectors in properties. 2.Create class for unionSet. 3.We use two for loops and compare all the vectors to find nodes, with edges. 4.Check each node, if it is parent of itself, it is root node so increase count of component. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { private: int intersect(vector<int>& a, vector<int>& b){ /*this is brute force for understanding gives tle on last taste case int ans = 0; unordered_set<int> sta(a.begin(),a.end()); unordered_set<int> stb(b.begin(),b.end()); for(auto it:sta){ if(stb.find(it) != stb.end()) ans++; } return ans;*/ int ans = 0; int i = 0, j = 0; while (i < a.size() && j < b.size()) { if (a[i] == b[j]) { ans++; int val = a[i]; // skip duplicates in both arrays while (i < a.size() && a[i] == val) i++; while (j < b.size() && b[j] == val) j++; } else if (a[i] < b[j]) { i++; } else { j++; } } return ans; } class unionFind{ public: vector<int> parent,size; unionFind(int n) : parent(n,-1),size(n,1) {} int find(int node){ if(parent[node] == -1){ return node; } return parent[node] = find(parent[node]); } void unionSet(int a,int b){ int pa = find(a); int pb = find(b); if(pa == pb) return; if(size[pa] > size[pb]){ parent[pb] = pa; size[pa] += size[pb]; } else{ parent[pa] = pb; size[pb] += size[pa]; } } }; public: int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); for (auto& v : properties) { sort(v.begin(), v.end()); } unionFind dsu(n); for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(intersect(properties[i],properties[j]) >= k){ dsu.unionSet(i,j); } } } int ans = 0; for(int i=0;i<n;i++){ if(dsu.find(i) == i){ ans++; } } return ans; } }; ```
1
0
['Two Pointers', 'Union Find', 'C++']
0
properties-graph
C++ Solution simple approach using graph construction and dfs
c-solution-simple-approach-using-graph-c-ad1r
ApproachFor the given constraints, following approach works fine. Construct a graph using the given approach and then find number of connected componentsComplex
kavya_naik
NORMAL
2025-03-23T14:17:58.853188+00:00
2025-03-23T14:19:45.868625+00:00
29
false
# Approach For the given constraints, following approach works fine. Construct a graph using the given approach and then find number of connected components # Complexity - Time complexity: $$O(n^2 * m * log(m))$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(n ^ 2)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); vector<vector<int>> graph = constructGraph(properties, k); vector<int> visited(n, 0); int connectedComponents = 0; for (int i = 0; i < n; ++i) { if (!visited[i]) { dfs(graph, i, visited); connectedComponents++; } } return connectedComponents; } private: void dfs(vector<vector<int>>& graph, int node, vector<int>& visited) { visited[node] = 1; for (auto u : graph[node]) { if (!visited[u]) { dfs(graph, u, visited); } } } vector<vector<int>> constructGraph(vector<vector<int>>& properties, int k) { int n = properties.size(); int m = properties[0].size(); vector<vector<int>> graph(n, vector<int>()); for (int i = 0; i < n; ++i) { set<int> s1; for (int l = 0; l < m; ++l) { s1.insert(properties[i][l]); } for (int j = i + 1; j < n; ++j) { set<int> s2; for (int l = 0; l < m; ++l) { if (s1.find(properties[j][l]) != s1.end()) { s2.insert(properties[j][l]); } } if (s2.size() >= k) { graph[i].push_back(j); graph[j].push_back(i); } } } return graph; } }; ```
1
0
['Array', 'Greedy', 'Depth-First Search', 'Graph', 'Ordered Set', 'Strongly Connected Component', 'C++']
0
properties-graph
๐Ÿงฉ๐Ÿค™๐Ÿป Count Connected Components Based on Shared Properties (Using DSU / Union Find)๐Ÿ’ฆ๐Ÿš€
count-connected-components-based-on-shar-e70i
IntuitionTo determine the number of connected components where each component is formed by groups of items sharing at least k common properties, we can treat th
udit_s05
NORMAL
2025-03-23T14:00:44.924474+00:00
2025-03-23T14:01:23.286586+00:00
26
false
# Intuition To determine the number of connected components where each component is formed by groups of items sharing at least k common properties, we can treat this as a graph problem. Each item is a node, and there is an edge between two nodes if they share k or more properties. This leads to the formation of disjoint sets of nodes, which we can track using a Disjoint Set Union (DSU) data structure. # Approach Disjoint Set (Union-Find): - We implement a Disjoint Set data structure supporting both union by rank and union by size. Here, unionBySize is used to merge groups. Preprocessing: - Convert each list of properties into a set for faster intersection checks. Pairwise Comparison: - For each pair of elements (i, j), compute how many properties they have in common using a helper function intersect(). - If the number of common properties is โ‰ฅ k, unite them in the DSU. Component Counting: - Finally, count how many unique parents exist in the DSU, which gives the number of components. # Complexity - Time complexity: - Let n be the number of items and m be the average number of properties per item. - Constructing the sets: O(n * m) - Pairwise comparisons: O(n^2 * m) in the worst case (due to intersect() doing set lookups) - DSU operations (with path compression and union by size): nearly constant time (amortized O(ฮฑ(n))) - Overall: O(n^2 * m) - Space complexity: - O(n * m) to store the property sets. - Additional O(n) for DSU structures (parent, rank, size). - Overall: O(n * m) # Code ```cpp [] class DisjointSet { public: vector<int> rank, parent, size; DisjointSet(int n) { rank.resize(n+1, 0); parent.resize(n+1); size.resize(n+1); for(int i = 0;i<=n;i++) { parent[i] = i; size[i] = 1; } } int findUPar(int node) { if(node == parent[node]) return node; return parent[node] = findUPar(parent[node]); } void unionByRank(int u, int v) { int ulp_u = findUPar(u); int ulp_v = findUPar(v); if(ulp_u == ulp_v) return; if(rank[ulp_u] < rank[ulp_v]) { parent[ulp_u] = ulp_v; } else if(rank[ulp_v] < rank[ulp_u]) { parent[ulp_v] = ulp_u; } else { parent[ulp_v] = ulp_u; rank[ulp_u]++; } } void unionBySize(int u, int v) { int ulp_u = findUPar(u); int ulp_v = findUPar(v); if(ulp_u == ulp_v) return; if(size[ulp_u] < size[ulp_v]) { parent[ulp_u] = ulp_v; size[ulp_v] += size[ulp_u]; } else { parent[ulp_v] = ulp_u; size[ulp_u] += size[ulp_v]; } } }; class Solution { public: int intersect(const unordered_set<int>& s1, const unordered_set<int>& s2){ int common = 0; if (s1.size() > s2.size()) {return intersect(s2, s1);} for(int x : s1){ {if(s2.count(x)) common++;} } return common; } int numberOfComponents(vector<vector<int>>& properties, int k) { int ans = 0, n = properties.size(); DisjointSet ds(n); vector<unordered_set<int>> sets(n); for(int i = 0; i < n; i++){ sets[i] = unordered_set<int>(properties[i].begin(), properties[i].end()); } for(int i=0; i<n; i++){ for(int j=i+1; j<properties.size(); j++){ if(intersect(sets[i], sets[j]) >= k){ ds.unionBySize(i, j); } } } for(int i=0; i<n; i++){ if(ds.findUPar(i) == i) ans++; } return ans; } }; ```
1
0
['Array', 'Union Find', 'Graph', 'Ordered Set', 'C++']
0
properties-graph
Oh really So much to do.
oh-really-so-much-to-do-by-madhavendrasi-9j8p
IntuitionFirst divide the part and then understand the concept.ApproachSo first make the function which return count of commman number and thenalso make dfs fu
Madhavendrasinh44
NORMAL
2025-03-23T12:39:03.055875+00:00
2025-03-23T12:39:03.055875+00:00
25
false
# Intuition First divide the part and then understand the concept. # Approach So first make the function which return count of commman number and thenalso make dfs function then sort the prop arrays and make them unique and thenmake the call for the common count then make the adjancent list. and then return the connected component # Complexity - Time complexity: $$O(n^2)$$ - Space complexity: $$O(n)$$ # Code ```cpp [] class Solution { public: int comman(vector<int>&a,vector<int>&b){ int i=0,j=0,cnt=0; while(i<a.size() and j<b.size()){ if(a[i]==b[j]){ cnt++,i++,j++; } else if(a[i]<b[j]){ i++; } else{ j++; } } return cnt; } void dfs(int a , vector<int>&vis,vector<vector<int>>&adj){ vis[a]=1; for(auto v : adj[a]){ if(vis[v])continue; dfs(v,vis,adj); } } int numberOfComponents(vector<vector<int>>& properties, int k) { for(int i=0;i<properties.size();i++){ sort(properties[i].begin(),properties[i].end()); properties[i].resize(unique(properties[i].begin(),properties[i].end())-properties[i].begin()); } vector<vector<int>> adj(properties.size()); for(int i=0;i<properties.size();i++){ for(int j=i+1;j<properties.size();j++){ int cnt=comman(properties[i],properties[j]); if(cnt>=k){ adj[i].push_back(j); adj[j].push_back(i); } } } int ans=0; vector<int>vis(properties.size(),0); for(int i=0;i<properties.size();i++){ if(vis[i])continue; dfs(i,vis,adj); ans++; } return ans; } }; ```
1
0
['Depth-First Search', 'Counting Sort', 'C++']
0
properties-graph
Beginner-Friendly || JAVA
beginner-friendly-java-by-gauraabhas-ifdo
IntuitionThe problem involves finding connected components based on shared properties between items. We can represent this as a graph problem, where nodes repre
gauraabhas
NORMAL
2025-03-23T10:29:04.641285+00:00
2025-03-23T10:29:04.641285+00:00
13
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem involves finding connected components based on shared properties between items. We can represent this as a graph problem, where nodes represent items, and edges exist between nodes if they share at least k common properties. # Approach <!-- Describe your approach to solving the problem. --> 1. Build the Graph: - Each item is treated as a node. - Use a helper function intersect() to count common elements between two property lists. - If two items share at least k common properties, an edge is created between them. - We store these edges in an adjacency list representation of the graph. 2. Find Connected Components: - Use Depth-First Search (DFS) to traverse the graph and count the number of connected components. - Maintain a visited array to track nodes that have been explored. - For each unvisited node, start a DFS traversal and mark all reachable nodes as visited. - Each DFS traversal represents discovering a new connected component. # Complexity - Time complexity: O(n^2*m) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n^2) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int intersect(int[] a,int[] b){ Set<Integer> A = new HashSet<>(); Set<Integer> B = new HashSet<>(); for(int i : a) A.add(i); for(int i : b) B.add(i); A.retainAll(B); return A.size(); } public int numberOfComponents(int[][] properties, int k) { int n = properties.length; List<List<Integer>> adj = new ArrayList<>(); for(int i=0;i<n;i++){ adj.add(new ArrayList<>()); } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(intersect(properties[i],properties[j]) >= k){ adj.get(i).add(j); adj.get(j).add(i); } } } boolean visited[] = new boolean[n]; int c = 0; for(int i=0;i<n;i++){ if(!visited[i]){ c++; dfs(i,adj,visited); } } return c; } public void dfs(int node ,List<List<Integer>> adj,boolean[] visited){ visited[node] = true; for(int nei : adj.get(node)){ if(!visited[nei]){ dfs(nei,adj,visited); } } } } ```
1
0
['Depth-First Search', 'Graph', 'Java']
0
properties-graph
Easy | C++ | Connected Components
easy-c-connected-components-by-wait_watc-w17a
IntuitionApproach Graph Construction: Treat each row in properties as a node. Use intersect() function to determine if two nodes are connected. If two rows sh
wait_watch
NORMAL
2025-03-23T09:55:05.439121+00:00
2025-03-26T13:30:59.773790+00:00
33
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> 1. **Graph Construction:** - Treat each row in `properties` as a node. - Use `intersect()` function to determine if two nodes are connected. - If two rows share at least `k` common elements, create an edge between them in the adjacency list. 2. **Intersection Function (`intersect`):** - Convert the first list into an unordered set. - Iterate over the second list and count how many elements exist in the set. - Remove elements from the set to ensure each element is counted only once. 3. **Finding Connected Components (`countConnectedComponents`):** - Use BFS to traverse the graph. - Maintain a `visited` array to track visited nodes. - For each unvisited node, start a BFS traversal and mark all reachable nodes. - Each BFS traversal represents a connected component. - Count the number of BFS traversals to get the total number of connected components. 4. **Main Function (`numberOfComponents`):** - Calls `numberOfConnectedComponents()` to compute the result. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: vector<int>g[110]; vector<bool>vis; int findCommon(unordered_map<int,int>&a, unordered_map<int,int>&b){ auto it = a.begin(); int ans =0; while(it!=a.end()){ if(b.count(it->first)) ans++; it++; } return ans; } void dfs(int u){ vis[u] = true; for(int v:g[u]){ if(!vis[v]){ dfs(v); } } } int numberOfComponents(vector<vector<int>>& p, int k) { vis = vector<bool>(p.size()+10,false); vector<unordered_map<int,int>>v; for(int i=0;i<p.size();i++){ unordered_map<int,int>curr; for(int j=0;j<p[i].size();j++){ curr[p[i][j]]++; } v.push_back(curr); } for(int i=0;i<p.size();i++){ for(int j=i+1;j<p.size();j++){ int ck = findCommon(v[i],v[j]); if(ck>=k){ g[i].push_back(j); g[j].push_back(i); } } } int ans =0; for(int i=0;i<p.size();i++){ if(!vis[i]){ dfs(i); ans++; } } return ans; } }; ```
1
0
['Graph', 'C++']
0
properties-graph
[Go, Python3] 0ms 9.26MB Fastest Go solution using Union Find and BitMask with explanations
go-python3-0ms-926-fastest-go-solution-u-u9ug
IntuitionWe need to count how many connected components exist in the graph, and the Union-Find (Disjoint Set Union) algorithm is a perfect fit for this type of
I4TL
NORMAL
2025-03-23T09:50:17.353364+00:00
2025-03-23T09:51:41.947896+00:00
20
false
![image.png](https://assets.leetcode.com/users/images/baf537e9-e2f1-464c-9667-6f1b85d846c6_1742723236.7539585.png) # Intuition We need to count how many connected components exist in the graph, and the **Union-Find** (Disjoint Set Union) algorithm is a perfect fit for this type of problem. Which is special about this problem is that we don't have neither adjacency list nor list of edges given to us as an input. Instead we are gives list of sets (although they are arrays, but problem states that "*...that returns the **number of distinct integers**...*" so we can simply ignore it and threat them as sets). We know the there's an edge between two vertices if they share **at least `k` common integers** (set intersection). # Approach 1. Representing Sets Efficiently with Bitsets Instead of using an array of maps `sets := []map[int]struct{}`, (which is relatively slow in Go), we use a **bitmask** representation. Given the constraint `(1 <= properties[i][j] <= 100)` we know the maximum integer is `100`. We need at least **100 slots**, which can be efficiently stored using **two** **`uint64` values** (providing 128 bits in total). or example, if a vertex is represented by the set `[1, 4, 5, 9]`, we encode it as a bitmask where the corresponding bit positions are set to `1`. `high = 000...000, low = ...100011001` This encoding allows us to efficiently check intersections using bitwise operations. We also initialize the `parent` and `rank` arrays for the Union-Find. 2. Building the Adjacency List We construct the adjacency list by comparing every pair of vertices. If two vertices share **at least `k` common elements**, we add an edge between them. To check for common elements, we use the bitwise AND operation between the corresponding low and high parts of their `BitSet` representation and count the number of `1` bits using the `bits.OnesCount64` function. 3. Union-Find with Path Compression We perform a classic Union-Find algorithm with path compression for efficient merging of components. Each time we successfully unite two components, we decrement the count of components n. By the end of this process, n will represent the number of connected components. # Complexity - Time complexity: $$O(n^2)$$ Constructing the bitsets: $$O(n \times m) $$ where n is the number of vertices and m is the maximum length of the sets (in this case, at most 100). Building the adjacency list: $$O(n^2)$$ since we compare all pairs of vertices. Union-Find operations: $$O(n \times \alpha(n) )$$ where $$\alpha(n)$$ is the inverse Ackermann function (amortized constant time). - Space complexity: $$O(n)$$ Bitsets: $$O(n)$$ (two uint64 per vertex). Union-Find arrays: $$O(n)$$ (parent and rank arrays). Adjacency list: $$O(E)$$ Where $$E$$ is the amound of edges. # Code ```golang [] type BitSet struct { low, high uint64 } func numberOfComponents(properties [][]int, k int) (r int) { n := len(properties) // 1. Initialize and fill main data structures sets := make([]BitSet, n) parent := make([]int, n) rank := make([]int, n) for idx, arr := range properties { parent[idx] = idx rank[idx] = 1 // use BitSet as bool array setting bit 1 if number is in set for _, v := range arr { if v < 64 {sets[idx].low |= (1 << v) } else {sets[idx].high |= (1 << (v - 64))} } } // 2. Build adjacency list by adding edges for all sets with at least k common integers adjList := make([][]int, n) for idxI, setI := range sets { for idxJ := idxI + 1; idxJ < n; idxJ++ { setJ := sets[idxJ] // check how many bits which are set to 1 are shared which is basically equivalent to set intersection if bits.OnesCount64(setI.low&setJ.low) + bits.OnesCount64(setI.high&setJ.high) >= k { adjList[idxI] = append(adjList[idxI], idxJ)} } } // 3. Union find functions declaration find := func(p int) int { for p != parent[p] { parent[p] = parent[parent[p]] p = parent[p] } return p } union := func(n1, n2 int) { a, b := find(n1), find(n2) if a == b {return} if rank[a] > rank[b] { rank[a] += rank[b] parent[b] = a n-- } else { rank[b] += rank[a] parent[a] = b n-- } } // Perform union on all edges we constructed previously for a, edges := range adjList { for _, b := range edges {union(a, b)} } return n } ``` I also provide simpler python code which uses simple sets for comparison, is some parts in Go look confusing. It's much slower, but still fast among python solution ![image.png](https://assets.leetcode.com/users/images/7a97a037-3e8c-4314-b4a9-2c14f128950a_1742723182.985351.png) ```python class Solution: def numberOfComponents(self, properties: List[List[int]], k: int) -> int: properties = [set(i) for i in properties] n = len(properties) adjList = defaultdict(list) for idx_i, i in enumerate(properties): for idx_j, j in enumerate(islice(properties, (_from:=idx_i+1), None), start=_from): if len(i.intersection(j)) >= k: adjList[idx_i].append(idx_j) parent = list(range(n)) rank = [1] * n def find(p): while p != parent[p]: parent[p] = parent[parent[p]] p = parent[p] return p def union(n1, n2): a, b = find(n1), find(n2) if a == b: return if rank[a] > rank[b]: rank[a] += rank[b] parent[b] = a self.components -= 1 else: rank[b] += rank[a] parent[a] = b self.components -= 1 self.components = n for a, v in adjList.items(): for b in v: union(a, b) return self.components ```
1
0
['Bit Manipulation', 'Union Find', 'Bitmask', 'Go', 'Python3']
0
properties-graph
Using BFS
using-bfs-by-udaykiran2427-kocx
IntuitionThe question is the algorithm! We have to follow the steps given: Write intersect(a, b), which counts common elements of both. For every array where i
udaykiran2427
NORMAL
2025-03-23T09:46:36.494271+00:00
2025-03-23T09:46:36.494271+00:00
20
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The question is the algorithm! We have to follow the steps given: 1. Write `intersect(a, b)`, which counts common elements of both. 2. For every array where `i != j`, check if `count >= k`. If true, create an edge between `i` and `j`. You can generate an adjacency list or matrix. 3. Count the connected components in the graph you just generated. You can use BFS/DFS/Disjoint Set. I used BFS in my solution. # Approach <!-- Describe your approach to solving the problem. --> - Construct a graph where an edge exists between two nodes if their intersection size is at least `k`. - Use BFS to count the number of connected components. # Complexity - **Time complexity:** - Constructing the graph: $$O(n^2 \cdot m)$$ (where $$m$$ is the max size of each array). - BFS traversal: $$O(n + E)$$, where $$E$$ is the number of edges. - Overall: $$O(n^2 \cdot m)$$ in the worst case. - **Space complexity:** - $$O(n^2)$$ for the adjacency list in the worst case. - $$O(n)$$ for the visited array. - Overall: $$O(n^2)$$ in the worst case. # Code ```cpp class Solution { int intersect(vector<int>& a, vector<int>& b) { set<int> st; for (int i : a) st.insert(i); int cnt = 0; for (int i : b) { if (st.find(i) != st.end()) { cnt++; st.erase(i); } } return cnt; } public: int numberOfComponents(vector<vector<int>>& prop, int k) { int n = prop.size(); int m = prop[0].size(); vector<vector<int>> adj(n); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (intersect(prop[i], prop[j]) >= k) { adj[i].push_back(j); adj[j].push_back(i); } } } int ans = 0; vector<int> vis(n, 0); for (int i = 0; i < n; i++) { if (!vis[i]) { ans++; queue<int> q; q.push(i); while (!q.empty()) { int node = q.front(); q.pop(); vis[node] = 1; for (int x : adj[node]) { if (!vis[x]) { q.push(x); vis[x] = 1; } } } } } return ans; } };
1
0
['Breadth-First Search', 'C++']
0
properties-graph
Create Adjacency List then DFS | O(N * M) in 3ms | Rust
create-adjacency-list-then-dfs-on-m-in-3-ndba
Complexity Time complexity: O(Nโˆ—M) Space complexity: O(Nโˆ—M) Code
Prog_Jacob
NORMAL
2025-03-23T05:08:42.371129+00:00
2025-03-23T05:08:42.371129+00:00
13
false
# Complexity - Time complexity: $$O(N * M)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(N * M)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```rust [] impl Solution { pub fn number_of_components(properties: Vec<Vec<i32>>, k: i32) -> i32 { let n = properties.len(); let mut adj = vec![vec![]; n]; let mut visited = vec![false; n]; let properties = properties.iter().map(|p| p.iter().fold(0u128, |acc, &x| acc | (1 << x)) ).collect::<Vec<_>>(); for i in 0..n { for j in 0..n { if i == j { continue }; if (properties[i] & properties[j]).count_ones() >= k as _ { adj[i].push(j); adj[j].push(i); } } } (0..n).filter(|&i| dfs(i, &adj, &mut visited)).count() as _ } } fn dfs(i: usize, adj: &Vec<Vec<usize>>, visited: &mut Vec<bool>) -> bool { if visited[i] { return false; } visited[i] = true; for &j in &adj[i] { dfs(j, adj, visited); } true } ```
1
0
['Rust']
0
properties-graph
Simple C++ with DFS
simple-c-with-dfs-by-prajakta_1510-ubqh
IntuitionApproachComplexity Time complexity: O(N^2 * M) Space complexity: O(N^2) + O(N) + O(M) Code
prajakta_1510
NORMAL
2025-03-23T04:47:36.213372+00:00
2025-03-23T04:47:36.213372+00:00
68
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(N^2 * M) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(N^2) + O(N) + O(M) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: void dfs(int node,vector<int>adj[],vector<int>&vis) { vis[node]=1; for(auto it : adj[node]) { if(!vis[it]) dfs(it,adj,vis); } } int fun(vector<int>adj[],int n) { vector<int>vis(n,0); int cnt=0; for(int i=0;i<n;i++) { if(!vis[i]) { dfs(i,adj,vis); cnt++; } } return cnt; } bool check(vector<int>&a, vector<int>&b,int k,int m) { set<int>st; int i=0,j=0; sort(a.begin(),a.end()); sort(b.begin(),b.end()); while(i<m && j<m) { if(a[i]==b[j]) { st.insert(a[i]); i++; j++; } else if(a[i]<b[j]) { i++; } else j++; } //cout<<st.size()<<endl; return st.size()>=k; } int numberOfComponents(vector<vector<int>>& prop, int k) { int n=prop.size(); vector<int>adj[n]; int m=prop[0].size(); // sort(prop.begin(),prop.end()); for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { if(check(prop[i],prop[j],k,m)) { adj[i].push_back(j); adj[j].push_back(i); } } } return fun(adj,n); } }; ```
1
0
['Graph', 'Sorting', 'C++']
0
properties-graph
Union Find + Bitmask, 4 ms Java Beats 100%.
union-find-bitmask-4-ms-java-beats-100-b-w7jl
Instead of entire hashsets, the limited scope of nums allows us to use two different longs to fit all 100 different nums into the 128 bits of the longs.This all
NickUlman
NORMAL
2025-03-23T04:47:00.070044+00:00
2025-03-23T04:47:00.070044+00:00
26
false
Instead of entire hashsets, the limited scope of nums allows us to use two different longs to fit all 100 different nums into the 128 bits of the longs. This allows us to calculate the intersection of any two rows unique vals by just taking the bitwise and of the masks. From here can just get the bitcount of the bitwise and and determine if it is >= threshold k to see if the intersection is large enough. # Code ```java [] class Solution { int[] id, sz; public int numberOfComponents(int[][] properties, int k) { int m = properties.length, n = properties[0].length; long[][] propMasks = new long[m][2]; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { propMasks[i][properties[i][j]/60] |= (1L << (properties[i][j] % 60)); } } id = new int[m]; sz = new int[m]; for(int i = 0; i < m; i++) { id[i] = i; sz[i] = 1; } for(int r = 0; r < m; r++) { for(int i = r+1; i < m; i++) { long intersectMask1 = (propMasks[r][0] & propMasks[i][0]), intersectMask2 = (propMasks[r][1] & propMasks[i][1]); int intersectSize = Long.bitCount(intersectMask1) + Long.bitCount(intersectMask2); if(intersectSize >= k) union(i, r); } } int comp = 0; for(int i = 0; i < m; i++) { if(find(i) == i) comp++; } return comp; } private int find(int p) { int root = p; while(id[root] != root) root = id[root]; while(p != root) { int next = id[p]; id[p] = root; p = next; } return root; } private void union(int p, int q) { p = find(p); q = find(q); if(p == q) return; if(sz[p] < sz[q]) { id[p] = q; sz[q] += sz[p]; } else { id[q] = p; sz[p] += sz[q]; } } } ```
1
0
['Bit Manipulation', 'Union Find', 'Java']
0
properties-graph
Simple Brute force | DSU
simple-brute-force-dsu-by-mayberon-dtfp
Code
MaybeRon
NORMAL
2025-03-23T04:37:56.435150+00:00
2025-03-23T04:37:56.435150+00:00
53
false
# Code ```cpp [] class Solution { public: struct DSU{ vector<int> par, chi; int components = 0; DSU(int n){ components = n; for(int i=0; i < n; i++){ par.push_back(i); chi.push_back(1); } } int getP(int n){ return par[n] = (par[n] == n ? n : getP(par[n])); } void join(int a, int b){ a = getP(a); b = getP(b); if(chi[a] >= chi[b]){ par[b] = a; chi[a] += chi[b]; } else{ par[a] = b; chi[b] += chi[a]; } components--; } int countComponents(){ return components; } }; int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); auto intersect = [](auto &a, auto &b)->int{ unordered_set<int> st(a.begin(), a.end()); int common=0; for(int x : b){ if(st.count(x)){ common++; st.erase(x); } } return common; }; DSU dsu(n); sort(properties.begin(), properties.end(), [](auto& a, auto& b) { return a.size() < b.size(); }); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n && properties[j].size() <= properties[i].size() + k; j++){ if(intersect(properties[i], properties[j]) >= k){ int par_u = dsu.getP(i); int par_v = dsu.getP(j); if(par_u != par_v){ dsu.join(i,j); } } } } return dsu.countComponents(); } }; ```
1
0
['Union Find', 'C++']
0
properties-graph
Best and easy solution to get an idea how to approach such Questions
best-and-easy-solution-to-get-an-idea-ho-3sq2
IntuitionComplexity Time complexity: O(nยฒ * m) Space complexity: Adjacency list: O(nยฒ) Visited array: O(n) HashSets: O(m) Recursion stack: O(n) Overall Space
cocwarrior16112004
NORMAL
2025-03-23T04:21:45.029844+00:00
2025-03-23T04:21:45.029844+00:00
37
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> just follow the question , use hashSet to find distinct common elements in the array , and after that connect those nodes to each other by adding them to the adj list , and its done. The graph is completed , now apply simple bfs and dfs too find the number of connected components. # Complexity - Time complexity: O(nยฒ * m) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: Adjacency list: O(nยฒ) Visited array: O(n) HashSets: O(m) Recursion stack: O(n) Overall Space Complexity: - O(nยฒ + m) (since O(nยฒ) dominates). <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int getCnt(int i , int j , int[][] properties ,int m ){ Set<Integer> a = new HashSet<>(); Set<Integer> b = new HashSet<>(); for(int k = 0 ; k < m ; k++){ a.add(properties[i][k]); b.add(properties[j][k]); } int cnt = 0; for(int p : a){ if(b.contains(p)) cnt++; } return cnt; } public void dfs(int node ,List<Integer>[] adj, boolean[] vis ){ vis[node]=true; for(int i: adj[node]){ if(!vis[i]){ dfs(i,adj,vis); } } } public int numberOfComponents(int[][] properties, int k) { int n = properties.length; int m = properties[0].length; List<Integer>[] adj = new ArrayList[properties.length]; for(int i = 0 ; i < n ; i++){ adj[i] = new ArrayList<>(); } for(int i = 0 ; i < n ; i++){ for(int j = 0 ; j < n ; j++){ if(i==j) continue; int cnt = getCnt(i,j,properties,m); if(cnt>=k){ adj[i].add(j); adj[j].add(i); } } } boolean vis[] = new boolean[n]; int cnt = 0; for(int i = 0 ; i < n ; i++){ if(!vis[i]){ dfs(i,adj,vis); cnt++; } } return cnt; } } ```
1
0
['Array', 'Hash Table', 'Depth-First Search', 'Java']
0
properties-graph
Easy to Understand - Queue + BFS - Python/Java/C++
easy-to-understand-queue-bfs-pythonjavac-tq2v
IntuitionApproachComplexity Time complexity: Space complexity: Note:While the Python and Java code execute successfully, the C++ code results in a TLE. Yet, wh
cryandrich
NORMAL
2025-03-23T04:13:20.817615+00:00
2025-03-23T04:13:20.817615+00:00
13
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> ## Note: While the Python and Java code execute successfully, the C++ code results in a TLE. Yet, when I run the C++ code specifically against the 667th test case, it succeeds? # Code ```java [] class Solution { public int numberOfComponents(int[][] properties, int k) { int n = properties.length; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i += 1) { adj.add(new ArrayList<>()); } for (int i = 0; i < n; i += 1) { for (int j = i + 1; j < n; j += 1) { if (intersect(properties[i], properties[j]) >= k) { adj.get(i).add(j); adj.get(j).add(i); } } } boolean[] visited = new boolean[n]; int count = 0; for (int i = 0; i < n; i += 1) { if (!visited[i]) { count += 1; Queue<Integer> queue = new LinkedList<>(); queue.offer(i); visited[i] = true; while (!queue.isEmpty()) { int current = queue.poll(); for (int neighbor : adj.get(current)) { if (!visited[neighbor]) { visited[neighbor] = true; queue.offer(neighbor); } } } } } return count; } private int intersect(int[] a, int[] b) { Set<Integer> setA = new HashSet<>(); for (int num : a) { setA.add(num); } Set<Integer> setB = new HashSet<>(); for (int num : b) { setB.add(num); } int count = 0; for (int num : setB) { if (setA.contains(num)) { count += 1; } } return count; } } ``` ```cpp [] class Solution { public: int intersect(const vector<int>& a, const vector<int>& b) { unordered_set<int> setA(a.begin(), a.end()); unordered_set<int> setB(b.begin(), b.end()); int count = 0; for (int num : setB) { if (setA.find(num) != setA.end()) { count += 1; } } return count; } int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); vector<vector<int>> adj(n); for (int u = 0; u < n; u += 1) { for (int v = u + 1; v < n; v += 1) { if (intersect(properties[u], properties[v]) >= k) { adj[u].push_back(v); adj[v].push_back(u); } } } vector<bool> visited(n, false); int count = 0; for (int i = 0; i < n; i += 1) { if (!visited[i]) { count += 1; queue<int> q; q.push(i); visited[i] = true; while (!q.empty()) { int current = q.front(); q.pop(); for (int neighbor : adj[current]) { if (!visited[neighbor]) { visited[neighbor] = true; q.push(neighbor); } } } } } return count; } }; ``` ```python [] class Solution: def intersect(self, a: List[int], b: List[int]) -> int: return len(set(a) & set(b)) def numberOfComponents(self, properties: List[List[int]], k: int) -> int: n = len(properties) adj = [[] for _ in range(n)] for u in range(n): for v in range(u + 1, n): if self.intersect(properties[u], properties[v]) >= k: adj[u].append(v) adj[v].append(u) visited = [False] * n count = 0 for i in range(n): if not visited[i]: count += 1 queue = deque([i]) visited[i] = True while queue: current = queue.popleft() for neighbor in adj[current]: if not visited[neighbor]: visited[neighbor] = True queue.append(neighbor) return count ```
1
0
['Breadth-First Search', 'Queue', 'C++', 'Java', 'Python3']
0
properties-graph
python code: it's work
python-code-its-work-by-bhav5sh-0e3w
IntuitionApproachComplexity Time complexity: Space complexity: Code
Bhav5sh
NORMAL
2025-03-23T04:10:38.694951+00:00
2025-03-23T04:10:38.694951+00:00
35
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def numberOfComponents(self, properties: List[List[int]], k: int) -> int: n = len(properties) adjlist = defaultdict(list) for i in range(n): for j in range(n): if i != j: if self.intersect(i, j, properties) >= k: adjlist[i].append(j) adjlist[j].append(i) count_component = 0 visited = [False] * n for i in range(n): if not visited[i]: self.bfs(i, visited, adjlist) count_component += 1 return count_component def intersect(self, i, j, properties): mp1 = {} for val in properties[i]: mp1[val] = True mp2 = {} for val in properties[j]: if val in mp1 and val not in mp2: mp2[val] = True return len(mp2) def bfs(self, src, visited, adjlist): q = deque() q.append(src) visited[src] = True while q: front = q.popleft() for neighbor in adjlist[front]: if not visited[neighbor]: q.append(neighbor) visited[neighbor] = True ```
1
0
['Hash Table', 'Breadth-First Search', 'Python3']
0
properties-graph
DSU || HashSet || Java
dsu-hashset-java-by-akshay_kadamm-dhta
IntuitionApproachComplexity Time complexity: Space complexity: Code
Akshay_Kadamm
NORMAL
2025-03-23T04:09:07.695553+00:00
2025-03-23T04:09:07.695553+00:00
19
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { class DSU { int[] parent, rank; DSU(int n) { parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; rank[i] = 1; } } int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } boolean union(int u, int v) { int rootU = find(u); int rootV = find(v); if (rootU == rootV) return false; if (rank[rootU] > rank[rootV]) { parent[rootV] = rootU; } else if (rank[rootU] < rank[rootV]) { parent[rootU] = rootV; } else { parent[rootV] = rootU; rank[rootU]++; } return true; } } public int numberOfComponents(int[][] properties, int k) { int n = properties.length; DSU dsu = new DSU(n); for (int i = 0; i < n; i++) { HashSet<Integer> set1 = new HashSet<>(); for (int num : properties[i]) { set1.add(num); } for (int j = i + 1; j < n; j++) { HashSet<Integer> set2 = new HashSet<>(); for (int num : properties[j]) { set2.add(num); } if (intersect(set1, set2) >= k) { dsu.union(i, j); } } } Set<Integer> unique = new HashSet<>(); for (int i = 0; i < n; i++) { unique.add(dsu.find(i)); } return unique.size(); } private int intersect(HashSet<Integer> set1, HashSet<Integer> set2) { int count = 0; for (int num : set1) { if (set2.contains(num)) { count++; } } return count; } } ```
1
0
['Java']
0
properties-graph
๐Ÿš€๐Ÿš€ Easy way ๐Ÿ”ฅ3493. Properties Graph ๐Ÿ‘‡
easy-way-3493-properties-graph-by-vanshn-s09k
IntuitionApproachComplexity Time complexity: Space complexity: Code
Vanshnigam
NORMAL
2025-03-23T04:06:48.399742+00:00
2025-03-23T04:06:48.399742+00:00
32
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class DSU { int p[]; int r[]; DSU(int n) { p = new int[n]; r = new int[n]; for (int i = 0; i < n; i++) p[i] = i; } public int find(int x) { if (x != p[x]) p[x] = find(p[x]); return p[x]; } public void union(int x, int y) { int a = find(x); int b = find(y); if (a == b) return; if (r[a] > r[b]) p[b] = a; else if (r[a] < r[b]) p[a] = b; else { p[b] = a; r[a]++; } } } class Solution { int intersect_check(Set<Integer> a, Set<Integer> b) { int c = 0; for (int num : a) { if (b.contains(num)) c++; } return c; } public int numberOfComponents(int[][] properties, int k) { int n = properties.length; DSU dsu = new DSU(n); List<Set<Integer>> List = new ArrayList<>(); for (int[] p : properties) { Set<Integer> s = new HashSet<>(); for (int num : p) s.add(num); List.add(s); } for (int x = 0; x < n; x++) { for (int y = x + 1; y < n; y++) { if (intersect_check(List.get(x), List.get(y)) >= k) { dsu.union(x, y); } } } Set<Integer> ans = new HashSet<>(); for (int i = 0; i < n; i++) { ans.add(dsu.find(i)); } return ans.size(); } } ```
1
0
['Greedy', 'Depth-First Search', 'Breadth-First Search', 'Union Find', 'Graph', 'Ordered Set', 'Java']
0
properties-graph
Easy Java Solution
easy-java-solution-by-vermaanshul975-7k5v
IntuitionApproachComplexity Time complexity: Space complexity: Code
vermaanshul975
NORMAL
2025-03-23T04:06:03.551976+00:00
2025-03-23T04:06:33.981312+00:00
12
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int numberOfComponents(int[][] properties, int k) { int n = properties.length; boolean[] vis = new boolean[n]; int components = 0; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) { adj.add(new ArrayList<>()); } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (intersect(properties[i], properties[j]) >= k) { adj.get(i).add(j); adj.get(j).add(i); } } } for (int i = 0; i < n; i++) { if (!vis[i]) { components++; dfs(adj, vis, i); } } return components; } private void dfs(List<List<Integer>> adj, boolean[] vis, int node) { vis[node] = true; for (int it : adj.get(node)) { if (!vis[it]){ dfs(adj,vis,it); } } } private int intersect(int[] a, int[] b) { Map<Integer, Integer> map = new HashMap<>(); for (int num : a) { map.put(num, map.getOrDefault(num, 1)); } int count = 0; for (int num : b) { if (map.containsKey(num) && map.get(num) > 0) { count++; map.put(num, map.get(num) - 1); } } return count; } } ```
1
0
['Java']
0
properties-graph
Java Disjoint Set Union
java-disjoint-set-union-by-adityachauhan-zycr
IntuitionApproachComplexity Time complexity: Space complexity: Code
adityachauhan_27
NORMAL
2025-03-23T04:05:24.661987+00:00
2025-03-23T04:05:24.661987+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int f(int[] a,int[] b){ HashSet<Integer> set=new HashSet<>(); for(int i:a){ set.add(i); } int cnt=0; for(int i:b){ if(set.contains(i)){ cnt++; set.remove(i); } } return cnt; } public int getPar(int x,int[] parent){ if(parent[x]==x)return x; parent[x]=getPar(parent[x],parent); return parent[x]; } public void union(int u,int v,int[] parent){ int ultpu=getPar(u,parent); int ultpv=getPar(v,parent); if(ultpu==ultpv){ return; }else{ parent[ultpv]=ultpu; } } public int numberOfComponents(int[][] properties, int k) { int n=properties.length; int[] parent=new int[n]; for(int i=0;i<n;i++){ parent[i]=i; } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(f(properties[i],properties[j])>=k){ union(i,j,parent); } } } int res=0; for(int i=0;i<n;i++){ if(parent[i]==i){ res++; } } return res; } } ```
1
0
['Union Find', 'Java']
0
properties-graph
Java | Set and DFS - Graph
java-set-and-dfs-graph-by-pankajj_42-b1cy
IntuitionApproachComplexity Time complexity: Space complexity: Code
Pankajj_42
NORMAL
2025-03-23T04:04:44.201885+00:00
2025-03-23T04:04:44.201885+00:00
14
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { private void dfs( int s, Map<Integer,List<Integer>> adjList, boolean[] vis ) { vis[s] = true; for( int adj : adjList.get(s) ) if( !vis[adj] ) dfs( adj, adjList, vis ); } public int numberOfComponents(int[][] properties, int k) { int n = properties.length; Map<Integer,List<Integer>> adjList = new HashMap<>(); for( int i=0; i<n; i++ ) { Set<Integer> iSet = Arrays.stream( properties[i] ) .boxed() .collect( Collectors.toSet() ); for( int j=i+1; j<n; j++ ) { Set<Integer> jSet = Arrays.stream( properties[j] ) .boxed() .collect( Collectors.toSet() ); jSet.retainAll( iSet ); if( jSet.size() >= k ) { adjList.putIfAbsent( i, new ArrayList<Integer>() ); adjList.putIfAbsent( j, new ArrayList<Integer>() ); adjList.get(i).add(j); adjList.get(j).add(i); } } } int res = 0; boolean[] vis = new boolean[n]; for( int i=0; i<n; i++ ) { if( !vis[i] ) { res++; if( adjList.containsKey(i) ) dfs( i, adjList, vis ); } } return res; } } ```
1
0
['Java']
0
properties-graph
Easy C++ solutionโœ…| comments added for explanationโœ…
easy-c-solution-comments-added-for-expla-8p27
Code
procrastinator_op
NORMAL
2025-03-23T04:04:30.342519+00:00
2025-03-23T04:04:30.342519+00:00
43
false
# Code ```cpp [] // standard dsu template class disjoint{ //for 0 based indexing vector<int> rank; vector<int> parent; vector<int> size; public: disjoint(int n){ rank.resize(n,0); size.resize(n,1); parent.resize(n,0); for (int i=0;i<n;i++){ parent[i]=i; } } void reset(int node){ parent[node]=node; } bool connected(int u,int v){ return (findParent(u)==findParent(v)); } int findParent(int u){ if (u==parent[u]){ return u; } return parent[u]=findParent(parent[u]); } void unionrank(int u,int v){ int pu=findParent(u); int pv=findParent(v); if (pu==pv){ return; } if (rank[pu]==rank[pv]){ parent[pv]=pu; rank[pu]++; } else if(rank[pu]<rank[pv]){ parent[pu]=pv; } else{ parent[pv]=pu; } } void unionsize(int u,int v){ int pu=findParent(u); int pv=findParent(v); if (pu==pv){ return; } if (size[pu] < size[pv]) { parent[pu] = pv; size[pv] += size[pu]; } else { parent[pv] = pu; size[pu] += size[pv]; } } }; class Solution { public: int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); // Initialize disjoint set for n nodes. disjoint d(n); // Create a 2D vector 'v' of size n x 101 (because properties values are in range [0, 100]) // and mark the occurrence of each integer in properties[i]. vector<vector<int>> v(n, vector<int>(101, 0)); for (int i = 0; i < n; i++) { for (auto j : properties[i]) v[i][j] = 1; // Mark that integer j is present in properties[i]. } // Compare each pair of properties. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int cnt = 0; // Counter for common distinct integers. // Iterate over all possible values from 0 to 100. for (int q = 0; q <= 100; q++) { // If integer 'q' is present in both properties[i] and properties[j], increment counter. if (v[i][q] == 1 && v[j][q] == 1) cnt++; } // If the number of common distinct integers is at least k, union the two nodes. if (cnt >= k) d.unionrank(i, j); } } // Use a set to collect unique representative parents of each component. set<int> ans; for (int i = 0; i < n; i++) { ans.insert(d.findParent(i)); } // The number of connected components is the size of the set. return ans.size(); } }; ```
1
0
['C++']
0
properties-graph
๐Ÿš€๐Ÿš€ Easy way ๐Ÿ”ฅ3493. Properties Graph ๐Ÿ‘‡
easy-way-3493-properties-graph-by-vanshn-k5fq
IntuitionApproachComplexity Time complexity: Space complexity: Code
Vanshnigam
NORMAL
2025-03-23T04:04:11.545949+00:00
2025-03-23T04:04:11.545949+00:00
31
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class DSU { int p[]; int r[]; DSU(int n) { p = new int[n]; r = new int[n]; for (int i = 0; i < n; i++) p[i] = i; } public int find(int x) { if (x != p[x]) p[x] = find(p[x]); return p[x]; } public void union(int x, int y) { int a = find(x); int b = find(y); if (a == b) return; if (r[a] > r[b]) p[b] = a; else if (r[a] < r[b]) p[a] = b; else { p[b] = a; r[a]++; } } } class Solution { int intersect_check(Set<Integer> a, Set<Integer> b) { int c = 0; for (int num : a) { if (b.contains(num)) c++; } return c; } public int numberOfComponents(int[][] properties, int k) { int n = properties.length; DSU dsu = new DSU(n); List<Set<Integer>> List = new ArrayList<>(); for (int[] p : properties) { Set<Integer> s = new HashSet<>(); for (int num : p) s.add(num); List.add(s); } for (int x = 0; x < n; x++) { for (int y = x + 1; y < n; y++) { if (intersect_check(List.get(x), List.get(y)) >= k) { dsu.union(x, y); } } } Set<Integer> ans = new HashSet<>(); for (int i = 0; i < n; i++) { ans.add(dsu.find(i)); } return ans.size(); } } ```
1
0
['Java']
1
properties-graph
|| โœ…#DAY_64th_Of_Daily_Codingโœ…||
day_64th_of_daily_coding-by-coding_with_-4m30
JAI SHREE DATNA๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™Code
Coding_With_Star
NORMAL
2025-03-23T04:02:11.929354+00:00
2025-03-23T04:05:32.425457+00:00
26
false
# JAI SHREE DATNA๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™ # Code ```cpp [] class Solution { public: class DSU { public: vector<int> parent, rank; DSU(int size) { parent.resize(size); rank.resize(size, 1); for (int i = 0; i < size; i++) { parent[i] = i; } } int findParent(int node) { if (parent[node] != node) { parent[node] = findParent(parent[node]); } return parent[node]; } void mergeSets(int node1, int node2) { int root1 = findParent(node1); int root2 = findParent(node2); if (root1 != root2) { if (rank[root1] > rank[root2]) { parent[root2] = root1; } else if (rank[root1] < rank[root2]) { parent[root1] = root2; } else { parent[root2] = root1; rank[root1]++; } } } }; int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); DSU dsu(n); // Precompute bitmask for each set vector<bitset<101>> bitmasks(n); for (int i = 0; i < n; i++) { for (int num : properties[i]) { bitmasks[i].set(num); // Set the bit at position `num` } } // Compare each pair of sets and merge if they share at least `k` common elements for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Count common elements using bitwise AND int common = (bitmasks[i] & bitmasks[j]).count(); if (common >= k) { dsu.mergeSets(i, j); } } } // Count the number of unique components unordered_set<int> uniqueComponents; for (int i = 0; i < n; i++) { uniqueComponents.insert(dsu.findParent(i)); } return uniqueComponents.size(); } }; ```
1
0
['C++', 'Java']
1
properties-graph
Union Find || Disjoint Set || O(n^2*m) || Faster than 99% || Clean Java Code
union-find-disjoint-set-on2m-faster-than-x0qe
Complexity Time complexity: O(n2โˆ—m) Space complexity: O(nโˆ—m) Code
youssef1998
NORMAL
2025-03-31T21:45:49.558162+00:00
2025-03-31T21:45:49.558162+00:00
1
false
# Complexity - Time complexity: $$O(n^2*m)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(n*m)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class DisjointSet { private final int[] root; private final int[] rank; private int count; public DisjointSet(int size) { root = new int[size]; rank = new int[size]; for (int i = 0; i < size; i++) { root[i] = i; rank[i] = 1; } } public int getCount() { Set<Integer> roots = new HashSet<>(); for (int i = 0; i < root.length; i++) { roots.add(find(i)); } return roots.size(); } public void union(int vertex1, int vertex2) { int root1 = find(vertex1); int root2 = find(vertex2); if (root1 != root2) { if (rank[root1] > rank[root2]) { root[root2] = root1; } else if (rank[root2] > rank[root1]) { root[root1] = root2; } else { root[root2] = root1; rank[root1]++; } } } private int find(int vertex) { if (root[vertex] == vertex) return vertex; return root[vertex] = find(root[vertex]); } } class Solution { public int numberOfComponents(int[][] properties, int k) { DisjointSet disjointSet = new DisjointSet(properties.length); for (int i = 0; i < properties.length; i++) { boolean[] distinct = new boolean[101]; for (int l = 0; l < properties[i].length; l++) { distinct[properties[i][l]] = true; } for (int j = i + 1; j < properties.length; j++) { long intersect = intersect(distinct, properties[j]); if (intersect >= k) { disjointSet.union(i, j); } } } return disjointSet.getCount(); } private long intersect(boolean[] prop1, int[] prop2) { long count = 0; boolean[] counted = new boolean[101]; for (int p : prop2) { if (prop1[p] && !counted[p]) { counted[p] = true; count++; } } return count; } } ```
0
0
['Array', 'Union Find', 'Graph', 'Java']
0
properties-graph
Java | JavaScript | TypeScript | C++ | C# | Kotlin | Go Solution.
java-javascript-typescript-c-c-kotlin-go-aazu
null
LachezarTsK
NORMAL
2025-03-31T17:28:04.612744+00:00
2025-03-31T17:48:15.853026+00:00
2
false
```Java [] public class Solution { private static final int BIT_SET_SUBGROUPS = 2; private static final int[] RANGE_OF_VALUES = {1, 100}; private int minNumberOfUniqueValueConnections; public int numberOfComponents(int[][] properties, int minNumberOfUniqueValueConnections) { this.minNumberOfUniqueValueConnections = minNumberOfUniqueValueConnections; long[][] bitSetGroups = createBitSetGroups(properties); return findNumberOfConnectedGroups(properties, bitSetGroups); } private long[][] createBitSetGroups(int[][] properties) { /* To keep the number of bit shifts within a 64-bit integer, each bitSetGroups[i] has: bitSetGroups[i][0] => stores unique values from 1 to 50 bitSetGroups[i][1] => stores unique values from 51 to 100 */ long[][] bitSetGroups = new long[properties.length][BIT_SET_SUBGROUPS]; for (int i = 0; i < properties.length; ++i) { for (int value : properties[i]) { int index = value / (RANGE_OF_VALUES[1] / BIT_SET_SUBGROUPS + 1); int bitShifts = 1 + value % (RANGE_OF_VALUES[1] / BIT_SET_SUBGROUPS + 1); long bitStamp = 1L << bitShifts; bitSetGroups[i][index] |= bitStamp; } } return bitSetGroups; } private int findNumberOfConnectedGroups(int[][] properties, long[][] bitSetGroups) { UnionFind unionFind = new UnionFind(properties.length); int numberOfComponents = properties.length; for (int i = 0; i < bitSetGroups.length; ++i) { for (int j = i + 1; j < bitSetGroups.length; ++j) { int totalConnections = 0; for (int g = 0; g < BIT_SET_SUBGROUPS; ++g) { totalConnections += countBitsSetToOne(bitSetGroups[i][g] & bitSetGroups[j][g]); } if (totalConnections >= minNumberOfUniqueValueConnections && unionFind.joinByRank(i, j)) { --numberOfComponents; } } } return numberOfComponents; } private int countBitsSetToOne(long value) { int bitsSetToOne = 0; while (value > 0) { bitsSetToOne += (value & 1); value >>= 1; } return bitsSetToOne; } } class UnionFind { private int[] parent; private int[] rank; UnionFind(int numberOfElements) { parent = new int[numberOfElements]; rank = new int[numberOfElements]; for (int i = 0; i < numberOfElements; ++i) { parent[i] = i; rank[i] = 1; } /* Alternatively: parent = IntStream.range(0, numberOfElements).toArray(); rank = new int[numberOfElements]; Arrays.fill(rank, 1); */ } private int findParent(int index) { if (parent[index] != index) { parent[index] = findParent(parent[index]); } return parent[index]; } boolean joinByRank(int indexOne, int indexTwo) { int first = findParent(indexOne); int second = findParent(indexTwo); if (first == second) { return false; } if (rank[first] >= rank[second]) { rank[first] += rank[second]; parent[second] = first; } else { rank[second] += rank[first]; parent[first] = second; } return true; } } ``` ```JavaScript [] /** * @param {number[][]} properties * @param {number} minNumberOfUniqueValueConnections * @return {number} */ var numberOfComponents = function (properties, minNumberOfUniqueValueConnections) { this.BIT_SET_SUBGROUPS = 4; this.RANGE_OF_VALUES = [1, 100]; this.minNumberOfUniqueValueConnections = minNumberOfUniqueValueConnections; const bitSetGroups = createBitSetGroups(properties); return findNumberOfConnectedGroups(properties, bitSetGroups); }; /** * @param {number[][]} properties * @return {number[][]} */ function createBitSetGroups(properties) { /* To keep the number of bit shifts within a 32-bit integer, each bitSetGroups[i] has: bitSetGroups[i][0] => stores unique values from 1 to 25 bitSetGroups[i][1] => stores unique values from 26 to 50 bitSetGroups[i][2] => stores unique values from 51 to 75 bitSetGroups[i][3] => stores unique values from 76 to 100 While the solutions in the other languages keep the number of bit shifts within a 64-bit integer, thus bitSetGroups[i] is divided into two parts, from 1 to 50 and from 51 to 100, in JavaScript, correspondingly in TypeScript, when performing bitwise operations on their standard number, implemented in double-precision 64-bit binary format IEEE 754, it is treated in a 32-bit binary format. To avoid overflowing, one option is to apply their inbuilt BigInt class (the less efficient option) or, as is done here, to divide the bitSetGroups[i] into four equal parts, so that the bit shifts do not exceed the 32-bit. */ const bitSetGroups = Array.from(new Array(properties.length), () => new Array(this.BIT_SET_SUBGROUPS).fill(0)); for (let i = 0; i < properties.length; ++i) { for (let value of properties[i]) { const index = Math.floor(value / (this.RANGE_OF_VALUES[1] / this.BIT_SET_SUBGROUPS + 1)); const bitShifts = 1 + (value % (this.RANGE_OF_VALUES[1] / this.BIT_SET_SUBGROUPS + 1)); const bitStamp = 1 << bitShifts; bitSetGroups[i][index] |= bitStamp; } } return bitSetGroups; } /** * @param {number[][]} properties * @param {number[][]} bitSetGroups * @return {number} */ function findNumberOfConnectedGroups(properties, bitSetGroups) { const unionFind = new UnionFind(properties.length); let numberOfComponents = properties.length; for (let i = 0; i < bitSetGroups.length; ++i) { for (let j = i + 1; j < bitSetGroups.length; ++j) { let totalConnections = 0; for (let g = 0; g < this.BIT_SET_SUBGROUPS; ++g) { totalConnections += countBitsSetToOne(bitSetGroups[i][g] & bitSetGroups[j][g]); } if (totalConnections >= this.minNumberOfUniqueValueConnections && unionFind.joinByRank(i, j)) { --numberOfComponents; } } } return numberOfComponents; } /** * @param {number} value * @return {number} */ function countBitsSetToOne(value) { let bitsSetToOne = 0; while (value > 0) { bitsSetToOne += (value & 1); value >>= 1; } return bitsSetToOne; } class UnionFind { #parent; #rank; /** * @param {number} numberOfElements */ constructor(numberOfElements) { this.#parent = new Array(numberOfElements); this.#rank = new Array(numberOfElements); for (let i = 0; i < numberOfElements; ++i) { this.#parent[i] = i; this.#rank[i] = 1; } /* Alternatively: this.parent = Array.from(Array(numberOfElements).keys()); this.rank = new Array(numberOfElements).fill(1); */ } /** * @param {number} index * @return {number} */ #findParent(index) { if (this.#parent[index] !== index) { this.#parent[index] = this.#findParent(this.#parent[index]); } return this.#parent[index]; } /** * @param {number} indexOne * @param {number} indexTwo * @return {boolean} */ joinByRank(indexOne, indexTwo) { const first = this.#findParent(indexOne); const second = this.#findParent(indexTwo); if (first === second) { return false; } if (this.#rank[first] >= this.#rank[second]) { this.#rank[first] += this.#rank[second]; this.#parent[second] = first; } else { this.#rank[second] += this.#rank[first]; this.#parent[first] = second; } return true; } } ``` ```TypeScript [] function numberOfComponents(properties: number[][], minNumberOfUniqueValueConnections: number): number { this.BIT_SET_SUBGROUPS = 4; this.RANGE_OF_VALUES = [1, 100]; this.minNumberOfUniqueValueConnections = minNumberOfUniqueValueConnections; const bitSetGroups = createBitSetGroups(properties); return findNumberOfConnectedGroups(properties, bitSetGroups); }; function createBitSetGroups(properties: number[][]): number[][] { /* To keep the number of bit shifts within a 32-bit integer, each bitSetGroups[i] has: bitSetGroups[i][0] => stores unique values from 1 to 25 bitSetGroups[i][1] => stores unique values from 26 to 50 bitSetGroups[i][2] => stores unique values from 51 to 75 bitSetGroups[i][3] => stores unique values from 76 to 100 While the solutions in the other languages keep the number of bit shifts within a 64-bit integer, thus bitSetGroups[i] is divided into two parts, from 1 to 50 and from 51 to 100, in JavaScript, correspondingly in TypeScript, when performing bitwise operations on their standard number, implemented in double-precision 64-bit binary format IEEE 754, it is treated in a 32-bit binary format. To avoid overflowing, one option is to apply their inbuilt BigInt class (the less efficient option) or, as is done here, to divide the bitSetGroups[i] into four equal parts, so that the bit shifts do not exceed the 32-bit. */ const bitSetGroups = Array.from(new Array(properties.length), () => new Array(this.BIT_SET_SUBGROUPS).fill(0)); for (let i = 0; i < properties.length; ++i) { for (let value of properties[i]) { const index = Math.floor(value / (this.RANGE_OF_VALUES[1] / this.BIT_SET_SUBGROUPS + 1)); const bitShifts = 1 + (value % (this.RANGE_OF_VALUES[1] / this.BIT_SET_SUBGROUPS + 1)); const bitStamp = 1 << bitShifts; bitSetGroups[i][index] |= bitStamp; } } return bitSetGroups; } function findNumberOfConnectedGroups(properties: number[][], bitSetGroups: number[][]): number { const unionFind = new UnionFind(properties.length); let numberOfComponents = properties.length; for (let i = 0; i < bitSetGroups.length; ++i) { for (let j = i + 1; j < bitSetGroups.length; ++j) { let totalConnections = 0; for (let g = 0; g < this.BIT_SET_SUBGROUPS; ++g) { totalConnections += countBitsSetToOne(bitSetGroups[i][g] & bitSetGroups[j][g]); } if (totalConnections >= this.minNumberOfUniqueValueConnections && unionFind.joinByRank(i, j)) { --numberOfComponents; } } } return numberOfComponents; } function countBitsSetToOne(value: number): number { let bitsSetToOne = 0; while (value > 0) { bitsSetToOne += (value & 1); value >>= 1; } return bitsSetToOne; } class UnionFind { private parent: number[]; private rank: number[]; constructor(numberOfElements: number) { this.parent = new Array(numberOfElements); this.rank = new Array(numberOfElements); for (let i = 0; i < numberOfElements; ++i) { this.parent[i] = i; this.rank[i] = 1; } /* Alternatively: this.parent = Array.from(Array(numberOfElements).keys()); this.rank = new Array(numberOfElements).fill(1); */ } private findParent(index: number): number { if (this.parent[index] !== index) { this.parent[index] = this.findParent(this.parent[index]); } return this.parent[index]; } joinByRank(indexOne: number, indexTwo: number): boolean { const first = this.findParent(indexOne); const second = this.findParent(indexTwo); if (first === second) { return false; } if (this.rank[first] >= this.rank[second]) { this.rank[first] += this.rank[second]; this.parent[second] = first; } else { this.rank[second] += this.rank[first]; this.parent[first] = second; } return true; } } ``` ```C++ [] #include <span> #include <vector> using namespace std; class UnionFind { vector<int> parent; vector<int> rank; public: UnionFind(int numberOfElements) { parent.resize(numberOfElements); rank.resize(numberOfElements); for (int i = 0; i < numberOfElements; ++i) { parent[i] = i; rank[i] = 1; } /* Alternatively: parent.resize(numberOfElements); ranges::iota(parent, 0); rank.resize(numberOfElements, 1); */ } int findParent(int index) { if (parent[index] != index) { parent[index] = findParent(parent[index]); } return parent[index]; } bool joinByRank(int indexOne, int indexTwo) { int first = findParent(indexOne); int second = findParent(indexTwo); if (first == second) { return false; } if (rank[first] >= rank[second]) { rank[first] += rank[second]; parent[second] = first; } else { rank[second] += rank[first]; parent[first] = second; } return true; } }; class Solution { static const int BIT_SET_SUBGROUPS = 2; static constexpr array<int, 2> RANGE_OF_VALUES = { 1, 100 }; int minNumberOfUniqueValueConnections{}; public: int numberOfComponents(vector<vector<int>>& properties, int minNumberOfUniqueValueConnections) { this->minNumberOfUniqueValueConnections = minNumberOfUniqueValueConnections; vector<vector<long long>> bitSetGroups = createBitSetGroups(properties); return findNumberOfConnectedGroups(properties, bitSetGroups); } private: vector<vector<long long>> createBitSetGroups(span<const vector<int>> properties) const { /* To keep the number of bit shifts within a 64-bit integer, each bitSetGroups[i] has: bitSetGroups[i][0] => stores unique values from 1 to 50 bitSetGroups[i][1] => stores unique values from 51 to 100 */ vector<vector<long long>> bitSetGroups(properties.size(), vector<long long>(BIT_SET_SUBGROUPS)); ; for (int i = 0; i < properties.size(); ++i) { for (int value : properties[i]) { int index = value / (RANGE_OF_VALUES[1] / BIT_SET_SUBGROUPS + 1); int bitShifts = 1 + value % (RANGE_OF_VALUES[1] / BIT_SET_SUBGROUPS + 1); long long bitStamp = 1LL << bitShifts; bitSetGroups[i][index] |= bitStamp; } } return bitSetGroups; } int findNumberOfConnectedGroups(span<const vector<int>> properties, span<const vector<long long>> bitSetGroups) const { UnionFind unionFind(properties.size()); int numberOfComponents = properties.size(); for (int i = 0; i < bitSetGroups.size(); ++i) { for (int j = i + 1; j < bitSetGroups.size(); ++j) { int totalConnections = 0; for (int g = 0; g < BIT_SET_SUBGROUPS; ++g) { totalConnections += countBitsSetToOne(bitSetGroups[i][g] & bitSetGroups[j][g]); } if (totalConnections >= minNumberOfUniqueValueConnections && unionFind.joinByRank(i, j)) { --numberOfComponents; } } } return numberOfComponents; } int countBitsSetToOne(long long value) const { int bitsSetToOne = 0; while (value > 0) { bitsSetToOne += (value & 1); value >>= 1; } return bitsSetToOne; } }; ``` ```C# [] using System; public class Solution { private static readonly int BIT_SET_SUBGROUPS = 2; private static readonly int[] RANGE_OF_VALUES = { 1, 100 }; private int minNumberOfUniqueValueConnections; public int NumberOfComponents(int[][] properties, int minNumberOfUniqueValueConnections) { this.minNumberOfUniqueValueConnections = minNumberOfUniqueValueConnections; long[][] bitSetGroups = CreateBitSetGroups(properties); return FindNumberOfConnectedGroups(properties, bitSetGroups); } private long[][] CreateBitSetGroups(int[][] properties) { /* To keep the number of bit shifts within a 64-bit integer, each bitSetGroups[i] has: bitSetGroups[i][0] => stores unique values from 1 to 50 bitSetGroups[i][1] => stores unique values from 51 to 100 */ long[][] bitSetGroups = new long[properties.Length][]; for (int i = 0; i < properties.Length; ++i) { bitSetGroups[i] = new long[BIT_SET_SUBGROUPS]; foreach (int value in properties[i]) { int index = value / (RANGE_OF_VALUES[1] / BIT_SET_SUBGROUPS + 1); int bitShifts = 1 + value % (RANGE_OF_VALUES[1] / BIT_SET_SUBGROUPS + 1); long bitStamp = 1L << bitShifts; bitSetGroups[i][index] |= bitStamp; } } return bitSetGroups; } private int FindNumberOfConnectedGroups(int[][] properties, long[][] bitSetGroups) { UnionFind unionFind = new UnionFind(properties.Length); int numberOfComponents = properties.Length; for (int i = 0; i < bitSetGroups.Length; ++i) { for (int j = i + 1; j < bitSetGroups.Length; ++j) { int totalConnections = 0; for (int g = 0; g < BIT_SET_SUBGROUPS; ++g) { totalConnections += CountBitsSetToOne(bitSetGroups[i][g] & bitSetGroups[j][g]); } if (totalConnections >= minNumberOfUniqueValueConnections && unionFind.JoinByRank(i, j)) { --numberOfComponents; } } } return numberOfComponents; } private int CountBitsSetToOne(long value) { int bitsSetToOne = 0; while (value > 0) { bitsSetToOne += (int)(value & 1); value >>= 1; } return bitsSetToOne; } } class UnionFind { private int[] parent; private int[] rank; public UnionFind(int numberOfElements) { parent = new int[numberOfElements]; rank = new int[numberOfElements]; for (int i = 0; i < numberOfElements; ++i) { parent[i] = i; rank[i] = 1; } /* Alternatively: parent = Enumerable.Range(0, numberOfElements).ToArray(); rank = new int[numberOfElements]; Array.Fill(rank, 1); */ } private int FindParent(int index) { if (parent[index] != index) { parent[index] = FindParent(parent[index]); } return parent[index]; } public bool JoinByRank(int indexOne, int indexTwo) { int first = FindParent(indexOne); int second = FindParent(indexTwo); if (first == second) { return false; } if (rank[first] >= rank[second]) { rank[first] += rank[second]; parent[second] = first; } else { rank[second] += rank[first]; parent[first] = second; } return true; } } ``` ```Kotlin [] class Solution { private companion object { const val BIT_SET_SUBGROUPS = 2 val RANGE_OF_VALUES = intArrayOf(1, 100) } private var minNumberOfUniqueValueConnections = 0 fun numberOfComponents(properties: Array<IntArray>, minNumberOfUniqueValueConnections: Int): Int { this.minNumberOfUniqueValueConnections = minNumberOfUniqueValueConnections val bitSetGroups: Array<LongArray> = createBitSetGroups(properties) return findNumberOfConnectedGroups(properties, bitSetGroups) } private fun createBitSetGroups(properties: Array<IntArray>): Array<LongArray> { /* To keep the number of bit shifts within a 64-bit integer, each bitSetGroups[i] has: bitSetGroups[i][0] => stores unique values from 1 to 50 bitSetGroups[i][1] => stores unique values from 51 to 100 */ val bitSetGroups = Array(properties.size) { LongArray(BIT_SET_SUBGROUPS) } for (i in properties.indices) { for (value in properties[i]) { val index = value / (RANGE_OF_VALUES[1] / BIT_SET_SUBGROUPS + 1) val bitShifts = 1 + value % (RANGE_OF_VALUES[1] / BIT_SET_SUBGROUPS + 1) val bitStamp : Long = 1L shl bitShifts bitSetGroups[i][index] = bitSetGroups[i][index] or bitStamp } } return bitSetGroups } private fun findNumberOfConnectedGroups(properties: Array<IntArray>, bitSetGroups: Array<LongArray>): Int { val unionFind = UnionFind(properties.size) var numberOfComponents = properties.size for (i in bitSetGroups.indices) { for (j in i + 1..<bitSetGroups.size) { var totalConnections = 0 for (g in 0..<BIT_SET_SUBGROUPS) { totalConnections += countBitsSetToOne(bitSetGroups[i][g] and bitSetGroups[j][g]) } if (totalConnections >= minNumberOfUniqueValueConnections && unionFind.joinByRank(i, j)) { --numberOfComponents } } } return numberOfComponents } private fun countBitsSetToOne(value: Long): Int { var bitsSetToOne = 0 var value: Long = value while (value > 0) { bitsSetToOne += (value and 1).toInt() value = value shr 1 } return bitsSetToOne } } class UnionFind(private val numberOfElements: Int) { private val parent = IntArray(numberOfElements) private val rank = IntArray(numberOfElements) init { for (i in 0..<numberOfElements) { parent[i] = i rank[i] = 1 } } /* Alternatively: private val parent = IntArray(numberOfElements) { i -> i } private val rank = IntArray(numberOfElements) { 1 } */ private fun findParent(index: Int): Int { if (parent[index] != index) { parent[index] = findParent(parent[index]) } return parent[index] } fun joinByRank(indexOne: Int, indexTwo: Int): Boolean { val first = findParent(indexOne) val second = findParent(indexTwo) if (first == second) { return false } if (rank[first] >= rank[second]) { rank[first] += rank[second] parent[second] = first } else { rank[second] += rank[first] parent[first] = second } return true } } ``` ```Go [] package main const BIT_SET_SUBGROUPS = 2 var RANGE_OF_VALUES = [2]int{1, 100} var minNumberOfUniqueValueConnections int func numberOfComponents(properties [][]int, minNumberOfConnections int) int { minNumberOfUniqueValueConnections = minNumberOfConnections var bitSetGroups [][]int64 = createBitSetGroups(properties) return findNumberOfConnectedGroups(properties, bitSetGroups) } func createBitSetGroups(properties [][]int) [][]int64 { /* To keep the number of bit shifts within a 64-bit integer, each bitSetGroups[i] has: bitSetGroups[i][0] => stores unique values from 1 to 50 bitSetGroups[i][1] => stores unique values from 51 to 100 */ bitSetGroups := make([][]int64, len(properties)) for i := range properties { bitSetGroups[i] = make([]int64, BIT_SET_SUBGROUPS) for _, value := range properties[i] { index := value / (RANGE_OF_VALUES[1] / BIT_SET_SUBGROUPS + 1) bitShifts := 1 + value % (RANGE_OF_VALUES[1] / BIT_SET_SUBGROUPS+1) bitStamp := int64(1) << bitShifts bitSetGroups[i][index] |= bitStamp } } return bitSetGroups } func findNumberOfConnectedGroups(properties [][]int, bitSetGroups [][]int64) int { unionFind := NewUnionFind(len(properties)) numberOfComponents := len(properties) for i := range bitSetGroups { for j := i + 1; j < len(bitSetGroups); j++ { totalConnections := 0 for g := range BIT_SET_SUBGROUPS { totalConnections += countBitsSetToOne(bitSetGroups[i][g] & bitSetGroups[j][g]) } if totalConnections >= minNumberOfUniqueValueConnections && unionFind.joinByRank(i, j) { numberOfComponents-- } } } return numberOfComponents } func countBitsSetToOne(value int64) int { bitsSetToOne := 0 for value > 0 { bitsSetToOne += int(value & 1) value >>= 1 } return bitsSetToOne } type UnionFind struct { parent []int rank []int } func NewUnionFind(numberOfElements int) *UnionFind { unionFind := &UnionFind{ parent: make([]int, numberOfElements), rank: make([]int, numberOfElements), } for i := range numberOfElements { unionFind.parent[i] = i unionFind.rank[i] = 1 } return unionFind } func (this *UnionFind) findParent(index int) int { if this.parent[index] != index { this.parent[index] = this.findParent(this.parent[index]) } return this.parent[index] } func (this *UnionFind) joinByRank(indexOne int, indexTwo int) bool { first := this.findParent(indexOne) second := this.findParent(indexTwo) if first == second { return false } if this.rank[first] >= this.rank[second] { this.rank[first] += this.rank[second] this.parent[second] = first } else { this.rank[second] += this.rank[first] this.parent[first] = second } return true } ```
0
0
['C++', 'Java', 'Go', 'TypeScript', 'Kotlin', 'JavaScript', 'C#']
0
properties-graph
12-line union find + bit masks, beats 99.65%
12-line-union-find-bit-masks-beats-9965-b4m0f
Complexity Time complexity: O(mโˆ—n) Space complexity: O(n) Submissionhttps://leetcode.com/problems/properties-graph/submissions/1591932651/Code
dsapelnikov
NORMAL
2025-03-31T10:53:35.931739+00:00
2025-03-31T10:53:35.931739+00:00
1
false
# Complexity - Time complexity: $$O(m*n)$$ - Space complexity: $$O(n)$$ # Submission https://leetcode.com/problems/properties-graph/submissions/1591932651/ # Code ```python3 [] class Solution: def numberOfComponents(self, properties: List[List[int]], k: int) -> int: # Union find: parents + parent getter with path compression parent = list(range(len(properties))) def get_parent(node): res = node while parent[res] != res: res = parent[res] parent[node] = res return res # Turn arrays into bit masks due to small range of values mask = [reduce(or_, [1 << o for o in pr]) for pr in properties] # Find disjoint sets using the union find algorithm for i, j in combinations(range(len(mask)), 2): if (mask[i] & mask[j]).bit_count() >= k: parent[get_parent(i)] = get_parent(j) # Return the number of root nodes in the parent graph return sum(i == parent[i] for i in range(len(parent))) ```
0
0
['Python3']
0
properties-graph
easiest java code !.......
easiest-java-code-by-coder_neeraj123-zga4
IntuitionApproachwe have to build the graph with the common elements of the two selected arrays , so iterate over the 2d array and select two arrays properties
coder_neeraj123
NORMAL
2025-03-31T07:25:38.338029+00:00
2025-03-31T07:25:38.338029+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. -->simply building the graph and counting the connected component # Approach <!-- Describe your approach to solving the problem. --> we have to build the graph with the common elements of the two selected arrays , so iterate over the 2d array and select two arrays properties[i] , properties[j] find there common elements and if they are >= k then i,j have an edge between them , after the graph is ready just apply dfs and count the connected components # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n^2 * m) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int numberOfComponents(int[][] properties, int k) { int n = properties.length; int m = properties[0].length; ArrayList<Integer> list[] = new ArrayList[n]; for (int i = 0; i < list.length; i++) { list[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for (int num : properties[i]) set1.add(num); for (int num : properties[j]) set2.add(num); set1.retainAll(set2); if (set1.size() >= k) { list[i].add(j); list[j].add(i); } } } int ans = helper(list); return ans; } public static int helper(ArrayList<Integer> list[]) { boolean vis[] = new boolean[list.length]; int count = 0; for (int i = 0; i < list.length; i++) { if (vis[i] != true) { count++; dfs(list, i, vis); } } return count; } public static void dfs(ArrayList<Integer> list[], int curr, boolean vis[]) { vis[curr] = true; for (int i = 0; i < list[curr].size(); i++) { int neigh = list[curr].get(i); if (vis[neigh] == false) { dfs(list, neigh, vis); } } } } ```
0
0
['Java']
0
properties-graph
Use sets to find edge condition and DSU to get no. of components
use-sets-to-find-edge-condition-and-dsu-xrcs0
IntuitionUse sets to find edge condition and DSU to get no. of componentsCode
akshar_
NORMAL
2025-03-30T08:16:33.871287+00:00
2025-03-30T08:16:33.871287+00:00
3
false
# Intuition Use sets to find edge condition and DSU to get no. of components # Code ```cpp [] class Solution { public: class DSU { public: int n; vector<int> parent, rank; DSU(int _n) { n = _n; parent.resize(n); rank.resize(n, 1); for (int i = 0; i < n; i++) { parent[i] = i; } } void combine(int x, int y) { int rx = find(x); int ry = find(y); if (rx == ry) { return; } if (rank[rx] > rank[ry]) { parent[ry] = rx; } else if (rank[ry] > rank[rx]) { parent[rx] = ry; } else { rank[rx]++; parent[ry] = rx; } } int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } }; int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); DSU dsu(n); vector<unordered_set<int>> sets; for (int i = 0; i < n; i++) { unordered_set<int> s(properties[i].begin(), properties[i].end()); sets.push_back(s); } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (edgeExists(sets[i], sets[j], k)) { dsu.combine(i, j); } } } unordered_set<int> roots; for (int i = 0; i < n; i++) { roots.insert(dsu.find(i)); } return roots.size(); } bool edgeExists(unordered_set<int> &s1, unordered_set<int> &s2, int k) { if (s1.size() < s2.size()) { return edgeExists(s2, s1, k); // iterate over smaller set for efficiency } int count = 0; for (int num : s2) { if (s1.find(num) != s1.end()) { // exists in both sets count++; } if (count >= k) { return true; } } return false; } }; ```
0
0
['Strongly Connected Component', 'C++']
0
properties-graph
C++ 79 ms
c-79-ms-by-eridanoy-7x07
IntuitionApproachComplexity Time complexity: Space complexity: Code
eridanoy
NORMAL
2025-03-29T21:50:50.419211+00:00
2025-03-29T21:50:50.419211+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool intersect(const vector<int>& a, const vector<int>& b, int k) { constexpr int len = 101; bool A[len] {}; for(auto i : a) A[i] = true; bool B[len] {}; for(auto i : b) B[i] = true; for(int i = 0; i < len; ++i) if(A[i] and B[i] and !--k) return true; return false; } void BFS(const vector<vector<int>>& graph, vector<bool>& visited, int curr) { queue<int> vertices; visited[curr] = true; vertices.push(curr); while(!vertices.empty()) { curr = vertices.front(); vertices.pop(); for(auto next : graph[curr]) { if(visited[next]) continue; visited[next] = true; vertices.push(next); } } } int numberOfComponents(const vector<vector<int>>& properties, const int k) { const int len = size(properties); vector<vector<int>> graph(len); for(int first = 0; first < len - 1; ++first) { for(int second = first + 1; second < len; ++second) { if(intersect(properties[first], properties[second], k)) { graph[first].push_back(second); graph[second].push_back(first); } } } int count = 0; vector<bool> visited(len); for(int i = 0; i < len; ++i) { if(visited[i]) continue; BFS(graph, visited, i); ++count; } return count; } }; ```
0
0
['C++']
0
properties-graph
Javascript union find 685ms
javascript-union-find-685ms-by-henrychen-ex1c
null
henrychen222
NORMAL
2025-03-29T16:08:58.695157+00:00
2025-03-29T16:08:58.695157+00:00
1
false
``` function DJSet(n) { let p = Array(n).fill(-1); return { find, union, count, equiv, par, grp } function find(x) { return p[x] < 0 ? x : p[x] = find(p[x]); } function union(x, y) { x = find(x); y = find(y); if (x == y) return false; if (p[x] < p[y]) [x, y] = [y, x]; p[x] += p[y]; p[y] = x; return true; } function count() { // total groups return p.filter(v => v < 0).length; } function equiv(x, y) { // isConnected return find(x) == find(y); } function par() { return p; } function grp() { // generate all groups (nlogn) let g = []; for (let i = 0; i < n; i++) g.push([]); for (let i = 0; i < n; i++) g[find(i)].push(i); // sorted and unique return g; } } const numberOfComponents = (p, k) => { let n = p.length, m = p[0].length, ds = new DJSet(n); for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { let cnt = intersect(p[i], p[j]); if (cnt >= k) ds.union(i, j); } } return ds.count(); }; const intersect = (a, b) => { let res = 0; a = new Set(a), b = new Set(b); for (const x of a) { if (b.has(x)) res++; } return res; }; ```
0
0
['Union Find', 'JavaScript']
0
properties-graph
union-find with path compression
union-find-with-path-compression-by-lamb-lmeu
Intuition typical union-find with path compression brute force to check edge/connection between two nodes/properties Code
lambdacode-dev
NORMAL
2025-03-29T01:21:57.485628+00:00
2025-03-29T01:21:57.485628+00:00
3
false
# Intuition - typical union-find with path compression - brute force to check edge/connection between two nodes/properties # Code ```cpp [] class Solution { public: int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); int m = properties[0].size(); vector<vector<bool>> masks(n, vector<bool>(101, false)); for(int i = 0; i < n; ++i) { for(auto j : properties[i]) { masks[i][j] = true; } } vector<int> parent(n); function<int(int)> find; find = [&find, &parent] (int i) { if(parent[i] == i) return i; return ( parent[i] = find(parent[i]) ); }; iota(parent.begin(), parent.end(), 0); for(int j = 1; j < n; ++j) { for(int i = 0; i < j; ++i) { int common = 0; for(int k = 1; k <= 100; ++k) { if(masks[i][k] && masks[j][k]) ++common; } if(common >= k) { parent[find(j)] = find(i); } } } unordered_set<int> groupIds; for(int j = 0; j < n; ++j) { groupIds.insert(find(j)); } return groupIds.size(); } }; ```
0
0
['C++']
0
properties-graph
Brute force to make edges and then graph visit
brute-force-to-make-edges-and-then-graph-ncft
Intuition brute force to check number of common numbers between two properties to make an edge if >= k. This takes < 100*100*100 steps. graph visited on the adj
lambdacode-dev
NORMAL
2025-03-29T00:59:11.521890+00:00
2025-03-29T00:59:11.521890+00:00
4
false
# Intuition - brute force to check number of common numbers between two properties to make an edge if `>= k`. This takes `< 100*100*100` steps. - graph visited on the adjacent list. - use `vector` instead of `unordered_map/set` as size is only `< 100` # Code ```cpp [] class Solution { public: int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); int m = properties[0].size(); vector<vector<bool>> nums(n, vector<bool>(101,false)); for(int i = 0; i < n; ++i) { for(auto p : properties[i]) { nums[i][p] = true; } } vector<vector<int>> adj(n); for(int i = 0; i < n; ++i) { for(int j = i+1; j < n; ++j) { int common = 0; for(int k = 0; k <= 100; ++k) { if(nums[i][k] && nums[j][k]) { ++common; } } if(common >= k) { adj[i].push_back(j); adj[j].push_back(i); } } } vector<bool> visited(n, false); function<void(int)> dfs; dfs = [&dfs, &visited, &adj](int i) { visited[i] = true; for(auto j : adj[i]) { if(!visited[j]) dfs(j); } }; int count = 0; for(int i = 0; i < n; ++i) { if(!visited[i]) { dfs(i); count++; } } return count; } }; ```
0
0
['C++']
0
properties-graph
[C++] Union Find || Bitset
c-union-find-bitset-by-daks_05-zsvf
IntuitionThe question states that there are n nodes 0 to n-1. Since There exists between node i to j only if intersect(properties[i], properties[j]) >= k, where
daks_05
NORMAL
2025-03-28T17:29:43.226656+00:00
2025-03-28T17:29:43.226656+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The question states that there are n nodes `0` to `n-1`. Since There exists between node `i` to `j` only if `intersect(properties[i], properties[j]) >= k`, where `intersect(a, b) that returns the number of distinct integers common to both arrays a and b`. The key thing is to compute `intersection` optimally, we can make use of bitset or any similar thing to do the same optimally represent presence of element in bitset and make use of `bitwise and`(&) to intersect those two We can either use Depth-first, Breath-first search or Union Find/ DisJoint set to find the number of components. # Approach <!-- Describe your approach to solving the problem. --> - Use a vector of bitset<100> - For each Property - Mark presence of each element in that property in the respective bitset. - Declare a DisJointset - for i from 0 until n - for j from i+1 until n - if (countSetBits(hash[i] & hash[j]) >= k) connect / union node i and j - return the number of components # Complexity - Time complexity: $$O(n^2)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(n)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class DisJointSet { int nC; vector<int> parent; public: vector<int> size; DisJointSet(int n) { nC = n; parent.resize(n); size.resize(n, 1); iota(parent.begin(), parent.end(), 0); } int find(int node) { if(node == parent[node]) return node; return parent[node] = find(parent[node]); } void unionSet(int u, int v) { int parU = find(u), parV = find(v); if(parU == parV) return ; if(size[parU] < size[parV]) { parent[parU] = parent[parV]; size[parV] += size[parU]; } else { parent[parV] = parent[parU]; size[parU] += size[parV]; } nC--; } int getNC() const { return nC; } }; class Solution { public: int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(), m = properties[0].size(); DisJointSet ds(n); bitset<100> intersection; vector<bitset<100>> hash(n); for(int i=0; i<n; i++) for(int j=0; j<m; j++) hash[i].set(properties[i][j] - 1); for(int i=0; i<n; i++) { for(int j=i+1; j<n; j++) { intersection = hash[i] & hash[j]; if(intersection.count() >= k) ds.unionSet(i, j); } } return ds.getNC(); } }; ```
0
0
['Hash Table', 'Bit Manipulation', 'Union Find', 'C++']
0
properties-graph
๐Ÿ”ฅ The Ultimate Union-Find Trick to Solve This in No Time! ๐Ÿ”ฅ
the-ultimate-union-find-trick-to-solve-t-drz0
IntuitionImagine each property as a galaxy in space. If two galaxies share enough stars (common elements), they form a galactic cluster (connected component). O
dngzz1
NORMAL
2025-03-28T12:22:53.069397+00:00
2025-03-28T12:22:53.069397+00:00
5
false
# Intuition Imagine each property as a galaxy in space. If two galaxies share enough stars (common elements), they form a galactic cluster (connected component). Our mission? Find the number of these clusters! ๐ŸŒŒ How do we do that? Graph + Union-Find Magic! ๐ŸŽฉโœจ # Approach Graph Representation: Each property list is a node. An edge exists between two nodes if their intersection has at least k elements. Union-Find for Clustering: We use path compression + union by rank to efficiently merge connected components. Every time we merge two components, the total count decreases. Final Count = Number of Clusters! ๐ŸŽฏ # Complexity - Time complexity: Intersection Check is $O(m)$ per pair. Graph construction is $O(n^2 m)$. Union-Find is almost $O(1)$, so the total is $O(n^2 m)$. - Space complexity: Union-Find takes $O(n)$ and sets for intersection takes $O(m)$ so the total is $O(n + m)$. # Code ```typescript [] function numberOfComponents(properties: number[][], k: number): number { const n = properties.length const m = properties[0].length let numComponents = n const unionFind = new UnionFind(n) for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { if (intersect(properties[i], properties[j]) >= k) { const unioned = unionFind.union(i, j) if (unioned) numComponents-- } } } return numComponents }; function intersect(a: number[], b: number[]): number { const setA = new Set(a) const setB = new Set(b) let count = 0 for (let num of setA) { if (setB.has(num)) count++ } return count } class UnionFind { parent: number[] rank: number[] constructor(n: number) { this.parent = Array.from({ length: n }, (_, i) => i) this.rank = new Array(n).fill(0) } find(i: number): number { if (this.parent[i] === i) return i return this.parent[i] = this.find(this.parent[i]) } union(i: number, j: number): boolean { const rootI = this.find(i) const rootJ = this.find(j) if (rootI === rootJ) return false if (this.rank[rootI] < this.rank[rootJ]) { this.parent[rootI] = rootJ } else if (this.rank[rootJ] < this.rank[rootI]) { this.parent[rootJ] = rootI } else { this.parent[rootI] = rootJ this.rank[rootJ]++ } return true } } ```
0
0
['TypeScript']
0
properties-graph
DSU soln
dsu-soln-by-rajanarora1999-ye04
IntuitionApproachComplexity Time complexity: Space complexity: Code
rajanarora1999
NORMAL
2025-03-28T08:33:56.898511+00:00
2025-03-28T08:33:56.898511+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool isedge(set <int> &a, set <int> &b,int k) {int ans=0; for(auto p:a) { if(b.find(p)!=b.end()) ans++; } return ans>=k; } int getparent(int a,vector <int> &parent) { if(a==parent[a]) return a; return parent[a]=getparent(parent[a],parent); } int numberOfComponents(vector<vector<int>>& properties, int k) { int n=properties.size(); vector <int> parent(n); vector <set<int> > op(n); for(int i=0;i<n;i++) { for(auto p:properties[i]) op[i].insert(p); } for(int i=0;i<n;i++) parent[i]=i; int ans=n; for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) { int x= getparent(i,parent),y=getparent(j,parent); if(x!=y and isedge(op[i],op[j],k)) { parent[x]=parent[y]; ans--; } } return ans; } }; ```
0
0
['C++']
0
properties-graph
simple python DFS solution
simple-python-dfs-solution-by-tejassheth-2i0m
IntuitionApproachComplexity Time complexity: Space complexity: Code
TejasSheth
NORMAL
2025-03-27T23:23:39.902250+00:00
2025-03-27T23:23:39.902250+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def numberOfComponents(self, properties: List[List[int]], k: int) -> int: graph = defaultdict(list) visited = set() res = 0 def intersect(a, b): return len(set(a) & set(b)) for i in range(len(properties) - 1): for j in range(i + 1, len(properties)): if intersect(properties[i], properties[j]) >= k: graph[i].append(j) graph[j].append(i) def dfs(idx): for neigh in graph[idx]: if neigh not in visited: visited.add(neigh) dfs(neigh) for i in range(len(properties)): if i not in visited: dfs(i) res += 1 return res ```
0
0
['Array', 'Hash Table', 'Depth-First Search', 'Graph', 'Python3']
0
properties-graph
Easy C++ Union Find | Beats 88.95%
easy-c-union-find-beats-8895-by-divs_div-u5zm
IntuitionWhen Quesion asks about no. of components and edges are supposed to be formed based on some condition , Think once along the line of Union FindApproach
Divs_Divs
NORMAL
2025-03-27T18:11:11.991316+00:00
2025-03-27T18:11:11.991316+00:00
5
false
# Intuition When Quesion asks about no. of components and edges are supposed to be formed based on some condition , Think once along the line of **Union Find** # Approach 1. Write the code of Union Find , cnt is to maintain no. of comoponents. Initially there ar en components as there are no edges formed 2. Take every pair of i and j and check the `intersect(a[i] ,a[j])`. If it has more than k elements, then form an edge between i and j. 3. intersect function - The "v" array is maintained for the elements seens in first array and then iterate over second array to find common elements. # Similar Problems [Number of Operations to Make Network Connected](https://leetcode.com/problems/number-of-operations-to-make-network-connected/description/) [Redundant Connection](https://leetcode.com/problems/redundant-connection/description/) --- # Code ```cpp [] class Solution { public: vector<int> parent, rank; int cnt; /* code for union find */ int find(int node) { if(node==parent[node]) return node; return parent[node] = find(parent[node]); } void makeset(int u , int v) { u =find(u); v=find(v); if(u==v) return ; if(rank[u] < rank[v]) parent[u] = v; else if(rank[v] < rank[u]) parent[v] = u; else if(rank[v]==rank[u]) {parent[v]=u; rank[u]++; } cnt--; // when a connection is made we reduce it because no. of components dec. by 1 } int intersect(vector<int> &a1 , vector<int> &a2) { vector<int> v(101 , 0); for(auto x:a1) v[x]++; int cnt =0; for(auto x:a2) { if(v[x]!=0) { cnt++; v[x] =0 ;// count only once } } return cnt; } int numberOfComponents(vector<vector<int>>& a, int k) { int n= a.size(); parent.resize(n); rank.resize(n); cnt = n; // right now n components for(int i=0; i<n; i++) parent[i]=i , rank[i]=0; for(int i=0; i<n ; i++) { for(int j= i+1; j<n; j++) { if(find(i)!= find(j))// if i and j are already not connected { if(intersect(a[i] , a[j]) >= k) { cout<<i<<" "<<j<<'\n'; makeset(i, j); } } } } return cnt; } }; ``` ![image.png](https://assets.leetcode.com/users/images/54230fda-3867-4343-a3f1-4f9562062c9e_1743099009.5535846.png)
0
0
['Union Find', 'Graph', 'C++']
0
properties-graph
just use union find ๐Ÿ™‚
just-use-union-find-by-shashanksaroj-vlav
IntuitionApproachComplexity Time complexity: Space complexity: Code
shashanksaroj
NORMAL
2025-03-27T16:03:01.384932+00:00
2025-03-27T16:03:01.384932+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; class Solution { class UnionFind { int[] parent; int count; public UnionFind(int count) { parent = new int[count]; for (int i = 0; i < count; i++) { parent[i] = i; } this.count = count; } public int find(int a) { int rootA = parent[a]; if (rootA != a) { rootA = find(rootA); } return rootA; } public void union(int a, int b) { int rootA = find(a); int rootB = find(b); if (rootA != rootB) { parent[rootB] = rootA; count--; } } public int getCount() { return count; } } public int numberOfComponents(int[][] properties, int k) { int n = properties.length; int m = properties[0].length; Map<Integer, Set<Integer>> mp = new HashMap<>(); for (int i = 0; i < n; i++) { int[] st = properties[i]; mp.put(i, Arrays.stream(st).boxed().collect(Collectors.toSet())); } int x = n; UnionFind uf = new UnionFind(x); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (isConnected(i, j, mp, k)) uf.union(i, j); } } return uf.getCount(); } private boolean isConnected(int i, int j, Map<Integer, Set<Integer>> mp, int k) { Set<Integer> intersectionSet = new HashSet<>(mp.get(i)); intersectionSet.retainAll(mp.get(j)); return intersectionSet.size() >= k; } } ```
0
0
['Java']
0
properties-graph
Easy to understand ...try once
easy-to-understand-try-once-by-chandak14-51z7
IntuitionApproachComplexity Time complexity: Space complexity: Code
chandak1427
NORMAL
2025-03-27T08:20:41.508534+00:00
2025-03-27T08:20:41.508534+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] import java.util.*; class Solution { class DisjointSet { List<Integer> par; List<Integer> size; DisjointSet(int n) { par = new ArrayList<>(); size = new ArrayList<>(); for (int i = 0; i < n; i++) { par.add(i); size.add(1); } } public int findUPar(int node) { if (par.get(node) == node) { return node; } int ul_par = findUPar(par.get(node)); par.set(node, ul_par); // Path Compression return ul_par; } public void unionBySize(int u, int v) { int ulp_u = findUPar(u); int ulp_v = findUPar(v); if (ulp_u == ulp_v) return; // Already in the same set if (size.get(ulp_u) >= size.get(ulp_v)) { size.set(ulp_u, size.get(ulp_u) + size.get(ulp_v)); par.set(ulp_v, ulp_u); // Merge v into u } else { size.set(ulp_v, size.get(ulp_u) + size.get(ulp_v)); par.set(ulp_u, ulp_v); // Merge u into v } } } public int numberOfComponents(int[][] properties, int k) { int n = properties.length; DisjointSet ds = new DisjointSet(n); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (intersect(properties[i], properties[j]) >= k) { ds.unionBySize(i, j); } } } Set<Integer> components = new HashSet<>(); for (int i = 0; i < n; i++) { components.add(ds.findUPar(i)); } return components.size(); } private int intersect(int[] a, int[] b) { Set<Integer> setA = new HashSet<>(); for (int num : a) { setA.add(num); } int count = 0; Set<Integer> intersected = new HashSet<>(); for (int num : b) { if (setA.contains(num) && !intersected.contains(num)) { count++; intersected.add(num); } } return count; } } ```
0
0
['Hash Table', 'Union Find', 'Graph', 'Java']
0
properties-graph
Beats 97%; Simple Counting and Storing Indices First and then DFS
beats-97-simple-counting-and-storing-ind-icvv
IntuitionApproachComplexity Time complexity: Space complexity: Code
Architava_Bhattacharya
NORMAL
2025-03-26T22:21:39.271573+00:00
2025-03-26T22:21:39.271573+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int numberOfComponents(int[][] properties, int k) { int n = properties.length, largest = 0; int[][] commons = new int[n][n]; for (int[] elements : properties) { for (int element : elements) { largest = Math.max(element, largest); } } List<List<Integer>> indices = new ArrayList<>(); for (int i = 0; i <= largest; i++) { indices.add(new ArrayList<>()); } for (int i = 0; i < properties.length; i++) { Set<Integer> unique = new HashSet<>(); for (int j = 0; j < properties[i].length; j++) { if (!unique.contains(properties[i][j])) { for (int element : indices.get(properties[i][j])) { commons[i][element]++; commons[element][i]++; } indices.get(properties[i][j]).add(i); unique.add(properties[i][j]); } } } List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) { adj.add(new ArrayList<>()); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (commons[i][j] >= k) { adj.get(i).add(j); } } } boolean vis[] = new boolean[n]; int components = 0; for (int i = 0; i < n; i++) { if (!vis[i]) { dfs(i, adj, vis); components++; } } return components; } public void dfs(int node, List<List<Integer>> adj, boolean[] vis) { vis[node] = true; for (int child : adj.get(node)) { if (!vis[child]) { dfs(child, adj, vis); } } } } ```
0
0
['Java']
0
properties-graph
TLE Issue Solution using minor changes
tle-issue-solution-using-minor-changes-b-bwnl
Approach Steps to solve tle issue; 1. instead of this:do this:2. instead of this:do this:Complexity Time complexity: Space complexity: Code
vasp0007
NORMAL
2025-03-26T21:20:36.536313+00:00
2025-03-26T21:20:36.536313+00:00
4
false
# Approach <!-- Describe your approach to solving the problem. --> > ## **Steps to solve tle issue;** $$1.$$ instead of this: ``` for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ adj[i].push_back(j); } } ``` do this: ``` for(int i=0; i<n; i++){ for(int j=i+1; j<n; j++){ adj[i].push_back(j); adj[j].push_back(i); } } ``` $$2.$$ instead of this: ``` int intersect(vector<int>&arr1, vector<int>&arr2){ unordered_set<int>hash1(arr1.begin(), arr1.end()); unordered_set<int>hash2(arr2.begin(), arr2.end()); int count = 0; for(auto it: hash2){ if(hash1.find(it)!=hash1.end()) count++; } return count; } ``` do this: ``` int intersect(vector<int>&arr1, vector<int>&arr2){ unordered_set<int>hash1(arr1.begin(), arr1.end()); int count = 0; for(auto it: arr2){ if(hash1.find(it)!=hash1.end()){ hash1.erase(it); count++; } } return count; } ``` # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int intersect(vector<int>&arr1, vector<int>&arr2){ unordered_set<int>hash1(arr1.begin(), arr1.end()); int count = 0; for(auto it: arr2){ if(hash1.find(it)!=hash1.end()){ hash1.erase(it); count++; } } return count; } void bfs(int node, vector<int>&vis, vector<vector<int>>&adj){ queue<int>q; vis[node] = 1; q.push(node); while(!q.empty()){ int currNode = q.front(); q.pop(); for(auto it: adj[currNode]){ if(!vis[it]){ vis[it] = 1; q.push(it); } } } } int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); vector<vector<int>>adj(n); for(int i=0; i<n; i++){ for(int j=i+1; j<n; j++){ if(i!=j){ if( intersect(properties[i], properties[j]) >= k){ adj[i].push_back(j); adj[j].push_back(i); } } } } vector<int>vis(n,0); int count = 0; for(int i=0; i<n; i++){ if(!vis[i]){ bfs(i,vis,adj); count++; } } return count; } }; ```
0
0
['Depth-First Search', 'Breadth-First Search', 'Graph', 'Ordered Set', 'C++']
0
properties-graph
Python
python-by-aravindankathi-0k5g
Complexity Time complexity: N*N Space complexity: O(N) Code
aravindankathi
NORMAL
2025-03-26T19:01:03.955616+00:00
2025-03-26T19:01:03.955616+00:00
1
false
# Complexity - Time complexity: N*N <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(N) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def numberOfComponents(self, properties: List[List[int]], k: int) -> int: def intersect(a, b): return len(list(set(a) & set(b))) dic = {} for i in range(len(properties)): dic[i] = [] for i in range(len(properties)): for j in range(i+1, len(properties)): if intersect(properties[i], properties[j]) >= k: dic[i].append(j) dic[j].append(i) component = 0 visited = [False] * len(properties) def dfs(node): if visited[node]: return visited[node] = True for nei in dic[node]: dfs(nei) for i in range(len(properties)): if not visited[i]: dfs(i) component += 1 return component ```
0
0
['Python3']
0
properties-graph
Python - short brute force with DFS
python-short-brute-force-with-dfs-by-ant-jj05
null
Ante_
NORMAL
2025-03-26T15:47:51.167614+00:00
2025-03-26T15:47:51.167614+00:00
2
false
``` class Solution: def numberOfComponents(self, p, k): props, g, n, res, seen = {i: set(a) for i, a in enumerate(p)}, defaultdict(set), len(p), 0, set() {g[i].add(j) or g[j].add(i) for i, j in combinations(range(n), 2) if len(props[i] & props[j]) >= k} def dfs(node): seen.add(node) [dfs(to) for to in g[node] if to not in seen] return sum(dfs(i) or 1 for i in range(n) if i not in seen) ```
0
0
['Array', 'Hash Table', 'Depth-First Search', 'Python3']
0
properties-graph
Easiest solution
easiest-solution-by-markandey_kumar-lsa1
IntuitiondfsApproach Find the intersection in both arrays and then form the list graph Now check no of disconnected graph that will be answer Code
markandey_kumar
NORMAL
2025-03-26T14:55:45.949407+00:00
2025-03-26T14:55:45.949407+00:00
1
false
# Intuition dfs # Approach 1. Find the intersection in both arrays and then form the list graph 2. Now check no of disconnected graph that will be answer # Code ```java [] class Solution { int intersect(int[] A, int[] B){ Set<Integer> set = new HashSet<>(); int count = 0; for(int x : A) set.add(x); for(int x : B){ if(set.contains(x)){ count++; set.remove(x); } } return count; } public void dfs(List<Integer> [] graph, int start, boolean[] vis){ vis[start] = true; for(int curr: graph[start]){ if(!vis[curr]){ dfs(graph, curr, vis); } } } public int numberOfComponents(int[][] p, int k) { int n = p.length; List<Integer> [] graph = new List[n]; for(int i = 0; i<n;i++) graph[i] = new ArrayList<>(); for(int i = 0; i<p.length; i++){ for(int j = i+1; j<p.length; j++){ if(intersect(p[i], p[j]) >= k){ System.out.println("hell"); graph[i].add(j); graph[j].add(i); } } } int ans = 0; boolean[] vis = new boolean[n]; for(int i = 0; i<n;i++){ if(!vis[i]){ dfs(graph, i, vis); ans++; } } return ans; } } ```
0
0
['Java']
0
properties-graph
Easiest solution using java
easiest-solution-using-java-by-markandey-wybp
IntuitionApproachComplexity Time complexity: Space complexity: Code
markandey_kumar
NORMAL
2025-03-26T14:52:42.447040+00:00
2025-03-26T14:52:42.447040+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { int intersect(int[] A, int[] B){ Set<Integer> set = new HashSet<>(); int count = 0; for(int x : A) set.add(x); for(int x : B){ if(set.contains(x)){ count++; set.remove(x); } } return count; } public void dfs(List<Integer> [] graph, int start, boolean[] vis){ vis[start] = true; for(int curr: graph[start]){ if(!vis[curr]){ dfs(graph, curr, vis); } } } public int numberOfComponents(int[][] p, int k) { int n = p.length; List<Integer> [] graph = new List[n]; for(int i = 0; i<n;i++) graph[i] = new ArrayList<>(); for(int i = 0; i<p.length; i++){ for(int j = i+1; j<p.length; j++){ if(intersect(p[i], p[j]) >= k){ System.out.println("hell"); graph[i].add(j); graph[j].add(i); } } } int ans = 0; boolean[] vis = new boolean[n]; for(int i = 0; i<n;i++){ if(!vis[i]){ dfs(graph, i, vis); ans++; } } return ans; } } ```
0
0
['Java']
0
properties-graph
DSU | Easy C++ Solution
dsu-easy-c-solution-by-krishiiitp-ikg7
Code
krishiiitp
NORMAL
2025-03-26T11:27:46.361888+00:00
2025-03-26T11:28:05.506820+00:00
3
false
# Code ```cpp [] class DisjointSet { private: vector < int > parent, rank; public: DisjointSet (int n) { parent.resize(n, 0); rank.resize(n, 0); for (int i = 0; i < n; i ++) { parent[i] = i; } } int findUp(int node) { if (parent[node] == node) { return node; } return parent[node] = findUp(parent[node]); } bool unionByRank(int a, int b) { int pa = findUp(a), pb = findUp(b); if (pa == pb) { return false; } if (rank[pa] > rank[pb]) { parent[pa] = pb; } else if (rank[pa] < rank[pb]) { parent[pb] = pa; } else { parent[pa] = pb; rank[pa] ++; } return true; } }; class Solution { public: int numberOfComponents(vector<vector<int>>& a, int k) { int n = a.size(), m = a[0].size(), ans = n; vector < vector < int > > dp (n, vector < int > (101, 0)); for (int i = 0; i < n; i ++) { for (int j = 0; j < m; j ++) { dp[i][a[i][j]]++; } } DisjointSet ds(n); for (int i = 0; i < n; i ++) { for (int j = i + 1; j < n; j ++) { int count = 0; for (int k = 1; k <= 100; k ++) { if(dp[i][k] && dp[j][k]) { count++; } } if (count >= k) { if (ds.unionByRank(i, j)) { ans --; } } } } return ans; } }; ```
0
0
['Array', 'Union Find', 'Graph', 'C++']
0
properties-graph
Python beats 99%. Union Find + Bit Set
python-beats-99-union-find-bit-set-by-te-np8y
IntuitionWhen a problem asks for the number of connected components, union-find should be at the top of your list for things to try. This problem is asking you
tet
NORMAL
2025-03-26T09:12:11.350565+00:00
2025-03-26T09:12:11.350565+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> When a problem asks for the number of connected components, union-find should be at the top of your list for things to try. This problem is asking you to build a graph where each node is a set of integers and there is an edge between every two nodes whose intersection is at least size k. Simply create sets from each list and intersect them to see whether they are connected. If they are union the components together. # Approach <!-- Describe your approach to solving the problem. --> First note that the numbers only go up to 100. We can use bit sets to represent the sets. Normal Python ints can be used as bit sets for relatively small numbers. Note that doing bit operations on really large numbers will be very slow, so consider implementing bit sets as a class when needed. For only 100 bits, normal ints will be fine. Convert each list of ints into a bit set. For each bit set, check if the intersection has at least k bits set. If so, union the indices. This step is where you can save a lot of time by using the built-in bit_count() method for ints. I get around 50 ms using this method and around 300 ms using the standard hamming weight algorithm which I left commented. I tried passing k and returning as soon as `c >= k`, but that was about the same. The bit_count method is implemented in c in cpython, so it runs a lot faster than a python implementation. Finally find the number of connected components by counting the number of unique parents. # Complexity $n$ is the number of properties, $m$ is the size of each property, $l$ is the largest value contained in a property. - Time complexity: $$O(n * m * l)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> The union-find complexity is dominated by the intersect complexity, so the reverse Ackermann function does not appear in the time complexity. - Space complexity: $$O(n * l)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> The number of bits used in each bit set scales with the largest value of all properties, albeit with a small constant factor. # Code ```python3 [] class Solution: def numberOfComponents(self, properties: List[List[int]], k: int) -> int: n = len(properties) self.parents = [i for i in range(n)] properties = [reduce(lambda x, y: x | (1 << y-1), prop, 0) for prop in properties] for i in range(n-1): for j in range(i+1, n): if self.intersect(properties[i], properties[j]) >= k: self.union(i, j) unique_parents = {self.find(i) for i in range(n)} return len(unique_parents) def intersect(self, a, b): return (a & b).bit_count() # n = a & b # c = 0 # while n: # n &= n-1 # c += 1 # return c def find(self, x): if x != self.parents[x]: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return self.parents[x] = y ``` ![image.png](https://assets.leetcode.com/users/images/3dc97673-b8a2-498b-86f6-7dd50b7302e1_1742978394.095297.png)
0
0
['Bit Manipulation', 'Union Find', 'Python', 'Python3']
0
properties-graph
easy cpp solution using bitset and DSU
easy-cpp-solution-using-bitset-and-dsu-b-kk5h
Code
singlaarshit
NORMAL
2025-03-25T12:34:41.444211+00:00
2025-03-25T12:34:41.444211+00:00
2
false
# Code ```cpp [] class DSU { public: vector<int> rank, parent; DSU(int n) { rank.resize(n + 1, 0); parent.resize(n + 1); for (int i = 0; i <= n; i++) { parent[i] = i; } } int find(int node) { if (node == parent[node]) { return node; } return parent[node] = find(parent[node]); } bool Union(int u, int v) { int ulp_u = find(u); int ulp_v = find(v); if (ulp_u == ulp_v) return false; // Already in the same set if (rank[ulp_u] < rank[ulp_v]) { parent[ulp_u] = ulp_v; } else if (rank[ulp_v] < rank[ulp_u]) { parent[ulp_v] = ulp_u; } else { parent[ulp_v] = ulp_u; rank[ulp_u]++; } return true; // Successful union } }; class Solution { static int intersect(const vector<int>& A, const vector<int>& B) { bitset<101> a, b; for (int x : A) a[x] = 1; for (int x : B) b[x] = 1; return (a & b).count(); } public: int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); DSU uf(n); int components = n; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (intersect(properties[i], properties[j]) >= k) { if (uf.Union(i, j)) { components--; } } } } return components; } }; ```
0
0
['C++']
0
properties-graph
Contest - 442 || Question-2
contest-442-question-2-by-sajaltiwari007-hetw
IntuitionApproachComplexity Time complexity: Space complexity: Code
sajaltiwari007
NORMAL
2025-03-25T10:21:39.269696+00:00
2025-03-25T10:21:39.269696+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class DSU{ List<Integer> parent = new ArrayList<>(); List<Integer> size = new ArrayList<>();// For Path Compression public DSU(int n){ for(int i=0;i<n;i++){ parent.add(i); size.add(1); } } public int find_Parent(int x){ if(parent.get(x)==x) return x; int x_parent = find_Parent(parent.get(x)); parent.set(x,x_parent); return parent.get(x); } public void take_union(int x , int y){ int x_parent = find_Parent(x); int y_parent = find_Parent(y); if(x_parent==y_parent) return; if(size.get(x_parent)>size.get(y_parent)){ parent.set(y_parent ,x_parent ); size.set(x_parent , size.get(x_parent)+size.get(y_parent)); } else{ parent.set(x_parent ,y_parent ); size.set(y_parent , size.get(x_parent)+size.get(y_parent)); } } public List<Integer> getParentList() { return parent; } public List<Integer> getSizeList() { return size; } } class Solution { public int numberOfComponents(int[][] nums, int k) { int n = nums.length; boolean[][] present = new boolean[n][101]; for (int i = 0; i < n; i++) { for (int num : nums[i]) { present[i][num] = true; } } DSU ds = new DSU(n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if(i==j) continue; int size = 0; for (int x = 1; x <= 100; x++) { if (present[i][x] && present[j][x]) { size++; } } if (size >= k) { ds.take_union(i, j); } } } List<Integer> list = ds.getParentList(); // System.out.println(list); HashSet<Integer> set = new HashSet<>(); for(int i:list) set.add(i); return set.size(); } } ```
0
0
['Union Find', 'Java']
0
properties-graph
C++
c-by-srv-er-nnfg
Code
srv-er
NORMAL
2025-03-25T08:32:36.539537+00:00
2025-03-25T08:32:36.539537+00:00
6
false
# Code ```cpp [] class Solution { public: bool isIntersected(vector<int> property_1, vector<int> property_2, int k) { bitset<101> mask_1, mask_2; for (auto& i : property_1) mask_1.set(i); for (auto& i : property_2) mask_2.set(i); mask_1 &= mask_2; int common = 0; for (int i = 0; i < 101; i++) if (mask_1[i]) ++common; return common >= k; } class DSU { vector<int> parent, height; int V; public: DSU(int n) { parent.resize(n); iota(parent.begin(), parent.end(), 0); height.resize(n, 1); V = n; } int find(int x) { if (x != parent[x]) return parent[x] = find(parent[x]); return x; } void unite(int u, int v) { int s1 = find(u), s2 = find(v); if (s1 == s2) { return; } if (height[s1] < height[s2]) { parent[s1] = s2; height[s2] += height[s1]; } else { parent[s2] = s1; height[s1] += height[s2]; } } int getConnectedComponents() { int comp = 0; for (int i = 0; i < V; i++) if (i == parent[i]) ++comp; return comp; } }; int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); DSU uf(n); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) if (isIntersected(properties[i], properties[j], k)) uf.unite(i, j); } return uf.getConnectedComponents(); } }; ```
0
0
['C++']
0
properties-graph
Using Two Set and Straightforward BFS Traversal
using-two-set-and-straightforward-bfs-tr-vqas
Approach1. Common Elements Calculation: The commonElement method uses two sets to track the elements of the two arrays. It then counts the number of common elem
hokteyash
NORMAL
2025-03-25T08:17:30.006642+00:00
2025-03-25T08:17:30.006642+00:00
2
false
# Approach ### 1. Common Elements Calculation: - The commonElement method uses two sets to track the elements of the two arrays. It then counts the number of common elements between the two sets. ### 2. Graph Construction: - An adjacency list is created to represent the graph. For each pair of properties, if the number of common elements is greater than or equal to k, an edge is added between the corresponding nodes. ### 3. Connected Components Calculation: - A straightforward BFS is used to traverse the graph and count the number of connected components. The bfs method marks all nodes reachable from a given node as visited. This approach ensures that we efficiently count the number of connected components in the graph based on the given conditions. # Code ```java [] class Solution { private int commonElement(int[] arr1, int[] arr2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for (int x : arr1) set1.add(x); for (int x : arr2) set2.add(x); int count = 0; for (int x : set2) { if (set1.contains(x)) count++; } return count; } private void bfs(boolean[] visited, int node, List<List<Integer>> adj) { Queue<Integer> queue = new LinkedList<>(); queue.offer(node); visited[node] = true; while (!queue.isEmpty()) { int iNode = queue.poll(); for (int x : adj.get(iNode)) { if (!visited[x]) { queue.offer(x); visited[x] = true; } } } } public int numberOfComponents(int[][] properties, int k) { int n = properties.length; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (commonElement(properties[i], properties[j]) >= k) { adj.get(i).add(j); adj.get(j).add(i); } } } boolean[] visited = new boolean[n]; int ans = 0; for (int i = 0; i < n; i++) { if (!visited[i]) { ans++; bfs(visited, i, adj); } } return ans; } } ```
0
0
['Breadth-First Search', 'Graph', 'Ordered Set', 'Java']
0
properties-graph
UnionFind
unionfind-by-ya_ah-9hcy
IntuitionApproachComplexity Time complexity: Space complexity: Code
ya_ah
NORMAL
2025-03-25T01:49:01.040201+00:00
2025-03-25T01:49:01.040201+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int numberOfComponents(int[][] properties, int k) { UnionFind uf = new UnionFind(properties.length); for (int i = 0; i < properties.length; i++) { Set<Integer> si = new HashSet<>(); for (int l : properties[i]) si.add(l); for (int j = i + 1; j < properties.length; j++) { Set<Integer> s = new HashSet<>(); for (int l : properties[j]) s.add(l); int jsize = s.size(); s.addAll(si); if (si.size() + jsize - k >= s.size()) uf.union(i, j); } } return uf.setsCount; } static class UnionFind { int n; int[] roots; int setsCount; UnionFind(int n) { this.n = n; roots = new int[n]; for (int i = 0; i < n; i++) roots[i] = i; setsCount = n; } boolean union(int a, int b) { int rootA = find(a); int rootB = find(b); if (rootA == rootB) return false; roots[b] = roots[rootB] = rootA; setsCount--; return true; } int find(int i) { if (roots[i] == i) return i; return roots[i] = find(roots[i]); } } } ```
0
0
['Java']
0
properties-graph
Python || union Find
python-union-find-by-vilaparthibhaskar-hh2y
IntuitionApproachComplexity Time complexity: Space complexity: Code
vilaparthibhaskar
NORMAL
2025-03-24T23:50:03.506604+00:00
2025-03-24T23:50:03.506604+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class UnionFind: def __init__(self, size): self.parent = list(range(size)) self.rank = [0] * size def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, x, y): rootX = self.find(x) rootY = self.find(y) if rootX == rootY: return False if self.rank[rootX] < self.rank[rootY]: self.parent[rootX] = rootY elif self.rank[rootX] > self.rank[rootY]: self.parent[rootY] = rootX else: self.parent[rootY] = rootX self.rank[rootX] += 1 return True class Solution: def numberOfComponents(self, properties: List[List[int]], k: int) -> int: n, m = len(properties), len(properties[0]) dp = [[0 for _ in range(n)] for _ in range(n)] def intersect(a, b): s = set(b) ans = 0 for i in set(a): if i in s: ans += 1 return ans for i in range(n): for j in range(i + 1, n): dp[i][j] = True if k <= intersect(properties[i], properties[j]) else False uf = UnionFind(n) for i in range(n): for j in range(i + 1, n): if dp[i][j]: uf.union(i, j) ans = 0 for i, j in enumerate(uf.parent): if i == j: ans += 1 return ans ```
0
0
['Array', 'Hash Table', 'Union Find', 'Graph', 'Python3']
0
properties-graph
UnionFind
unionfind-by-linda2024-ukx2
IntuitionApproachComplexity Time complexity: Space complexity: Code
linda2024
NORMAL
2025-03-24T22:26:45.941687+00:00
2025-03-24T22:26:45.941687+00:00
8
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```csharp [] public class Solution { private bool ValidComm(HashSet<int> h1, HashSet<int> h2, int k) { int len1 = h1.Count, len2 = h2.Count; if(len1 > len2) return ValidComm(h2, h1, k); if(len1 < k) return false; foreach(int cur in h1) { if(h2.Contains(cur)) k--; } return k <= 0; } private int[] par; private int FindPar(int x) { if(par[x] != x) par[x] = FindPar(par[x]); return par[x]; } private void Union(int x, int y) { int parX = FindPar(x), parY = FindPar(y); par[parX] = par[parY]; } public int NumberOfComponents(int[][] properties, int k) { int n = properties.Length, res = 0; par = Enumerable.Range(0, n).ToArray(); bool[,] dp = new bool[n, n]; HashSet<int> visited = new(); for(int i = 0; i < n; i++) { for(int j = i+1; j < n; j++) { if(ValidComm(properties[i].ToHashSet(), properties[j].ToHashSet(), k)) Union(i, j); } } HashSet<int> parSets = new(); for(int i = 0; i < n; i++) { int curPar = FindPar(i); Console.WriteLine($"{i}th item's par is {curPar}"); parSets.Add(curPar); } return parSets.Count; } } ```
0
0
['C#']
0
properties-graph
transfer vectors in unordered_set + BFS (C++)
transfer-vectors-in-unordered_set-bfs-c-pz3h1
ApproachTransfer vectors in properties to unordered_set in order to efficiently find edges in graph prapering process, after that just do bfs over the graph in
xelladze
NORMAL
2025-03-24T20:24:32.159098+00:00
2025-03-24T20:26:05.930847+00:00
2
false
# Approach <!-- Describe your approach to solving the problem. --> Transfer vectors in properties to unordered_set<int> in order to efficiently find edges in graph prapering process, after that just do bfs over the graph in order to find connected components. # Complexity - Time complexity:O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(N) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int numberOfComponents(vector<vector<int>>& properties, int k) { int ans = 0; int n = properties.size(); vector <vector <int>> graph (n, vector <int>()); vector<unordered_set<int>> vc; for(auto & it : properties) vc.push_back({it.begin(), it.end()}); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(i == j) continue; if(intersact(vc[i], vc[j]) >= k){ graph[i].push_back(j); graph[j].push_back(i); } } } vector <bool> visited (n, false); for(int i = 0; i < n; i++){ if(!visited[i]){ ans++; queue<int> que; que.push(i); visited[i] = true; while(!que.empty()){ int u = que.front(); que.pop(); for(auto & v : graph[u]){ if(!visited[v]){ visited[v] = true; que.push(v); } } } } } return ans; } int intersact(unordered_set <int> &a, unordered_set <int> &b){ int count = 0; for(auto & it : b) if(a.find(it) != a.end()) count++; return count; } }; ```
0
0
['C++']
0
properties-graph
Java || DFS || Beats 100%
java-dfs-beats-100-by-dipankarsethi3012-l95i
IntuitionApproachComplexity Time complexity: Space complexity: Code
dipankarsethi3012
NORMAL
2025-03-24T17:24:11.697633+00:00
2025-03-24T17:24:11.697633+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int numberOfComponents(int[][] properties, int k) { int n = properties.length; Map<Integer, List<Integer>> mp = new HashMap<>(); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(i == j) continue; int res = intersect(properties[i], properties[j]); if(res >= k) { mp.putIfAbsent(i, new ArrayList<>()); mp.putIfAbsent(j, new ArrayList<>()); mp.get(i).add(j); mp.get(j).add(i); } } } boolean[] visited = new boolean[n]; int count = 0; for(int i = 0; i < n; i++) { if(!mp.containsKey(i)) { count++; continue; } if(visited[i]) continue; count++; dfs(mp, i, visited); } return count; } private int intersect(int[] a, int[] b) { Set<Integer> st = new HashSet<>(); Set<Integer> visited = new HashSet<>(); for(int i : a) { st.add(i); } int c = 0; for(int i : b) { if(st.contains(i) && !visited.contains(i)) { c++; visited.add(i); } } return c; } private void dfs(Map<Integer, List<Integer>> mp, int node, boolean[] visited) { visited[node] = true; if(!mp.containsKey(node)) return; for(int nbr : mp.get(node)) { if(visited[nbr]) continue; dfs(mp, nbr, visited); } } } ```
0
0
['Java']
0
properties-graph
Easy JAVA Solution using Sets and BFS
easy-java-solution-using-sets-and-bfs-by-kk41
Code
Debrup7703
NORMAL
2025-03-24T13:49:01.807764+00:00
2025-03-24T13:49:01.807764+00:00
1
false
# Code ```java [] class Solution { public int numberOfComponents(int[][] properties, int k) { int n=properties.length; List<List<Integer>> adj=new ArrayList<>(); for(int i=0;i<=n;i++) adj.add(new ArrayList<Integer>()); HashMap<Integer,HashSet<Integer>> map=new HashMap<>(); for(int i=0;i<properties.length;i++){ HashSet<Integer> h=new HashSet<>(); for(int j:properties[i]) h.add(j); map.put(i,h); } for(int i=0;i<properties.length;i++){ HashSet<Integer> hs1=map.get(i); for(int j=i+1;j<properties.length;j++){ HashSet<Integer> hs2=map.get(j); HashSet<Integer> in=new HashSet<>(); for(int l:hs2){ if(hs1.contains(l)) in.add(l); } if(in.size()>=k){ adj.get(i).add(j); adj.get(j).add(i); } } } int[] vis=new int[n]; int ans=0; for(int i=0;i<n;i++){ if(vis[i]==1) continue; ans++; Queue<Integer> q=new LinkedList<Integer>(); q.offer(i); vis[i]=1; while(!q.isEmpty()){ int curr=q.peek(); q.remove(); for(int j:adj.get(curr)){ if(vis[j]==1) continue; q.offer(j); vis[j]=1; } } } return ans; } } ```
0
0
['Hash Table', 'Breadth-First Search', 'Graph', 'Java']
0
properties-graph
8 lines scala disjoint-set / union-find solution
8-lines-scala-disjoint-set-union-find-so-mgfj
null
vititov
NORMAL
2025-03-24T11:24:19.758311+00:00
2025-03-24T11:24:19.758311+00:00
1
false
```scala [] object Solution { import scala.util.chaining._ def numberOfComponents(properties: Array[Array[Int]], k: Int): Int = { val djs = properties.indices.to(Array) def root(i:Int): Int = if(djs(i)==i) i else root(djs(i)).tap(djs(i) = _) def join(i:Int)(j:Int) = (djs(root(j))=root(i)) properties.map(_.to(Set)).to(List).zipWithIndex.tails.filter(_.nonEmpty) .flatMap{t => t.head pipe {case (aSet,i) => t.tail.collect{ case (bSet,j) if (aSet intersect bSet).size >= k => (i,j)} }}.foreach{case (i,j) => join(i)(j)} djs.indices.map(root).distinct.size } } ```
0
0
['Hash Table', 'Greedy', 'Union Find', 'Graph', 'Scala']
0
properties-graph
๐Ÿ˜€100% User Beat | ๐Ÿ’ก DFS | Java
100-user-beat-dfs-java-by-s_a_m2003-bh80
IntuitionApproachComplexity Time complexity: Space complexity: Code
s_a_m2003
NORMAL
2025-03-24T10:57:32.722390+00:00
2025-03-24T10:57:32.722390+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { Map<Integer,List<Integer>> graph = new HashMap<>(); public int numberOfComponents(int[][] properties, int k) { int v = properties.length; for(int i = 0 ; i < v; i++){ graph.put(i,new ArrayList<>()); } for(int i = 0 ; i < v; i++){ for(int j = 0; j < v; j++){ if(i != j && checkIntersection(properties[i],properties[j],k)){ addEdge(graph,i,j); } } } int cc = connectedComponent(graph, v); System.out.println(cc); return cc; } public boolean checkIntersection(int arr1[], int arr2[], int k){ Arrays.sort(arr1); Arrays.sort(arr2); int i = 0; int j = 0; Set<Integer> set = new HashSet<>(); while(i < arr1.length && j < arr2.length){ if(arr1[i] == arr2[j]){ set.add(arr1[i]); i++; j++; } else if(arr1[i] > arr2[j]){ j++; }else{ i++; } } if(set.size() >= k){ return true; } return false; } public void addEdge(Map<Integer,List<Integer>> graph, int v1, int v2){ graph.get(v1).add(v2); graph.get(v2).add(v1); } public int connectedComponent(Map<Integer,List<Integer>> graph,int v) { // one thing that you know Graph is disconnected(Some of them are connected) // to go on each starting node you have to create an array of visited array int visited[] = new int[v]; // after that i will try to find all possible diconnected component via // using visited array... int count = 0; for(int i = 0; i < visited.length; i++){ if(visited[i] == 0){ count++; dfs(graph,visited,i); } } return count; } public void dfs(Map<Integer,List<Integer>> graph, int []visited,int src){ Stack<Integer> stack = new Stack<>(); stack.push(src); while(!stack.isEmpty()){ int v = stack.pop(); if(visited[v] == 1){ continue; } visited[v] = 1; for(int nbrs : graph.get(v)){ if(visited[nbrs] != 1){ stack.push(nbrs); } } } } } ```
0
0
['Depth-First Search', 'Graph', 'Java']
0
properties-graph
Simple bitset + dfs || c++
simple-bitset-dfs-c-by-subhamchauhan1100-ov1s
IntuitionApproachComplexity Time complexity: Space complexity: Code
subhamchauhan1100
NORMAL
2025-03-24T09:43:41.959474+00:00
2025-03-24T09:43:41.959474+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: vector<int> adj[101]; vector<bool> visited = vector<bool>(101, false); void dfs(int v) { visited[v] = true; for (int u : adj[v]) { if (!visited[u]) dfs(u); } } static int intersect(const auto& A, const auto& B){ return (A&B).count(); } int numberOfComponents(vector<vector<int>>& p, int k) { int n =p.size(),m=p[0].size(); vector<bitset<101>> A(n, 0); int i=0; for(auto& a: p){ for(int x: a) A[i][x]=1; i++; } for(int i =0;i<n;i++) { for(int j=0;j<n;j++) { const auto& X=A[i]; const auto& Y=A[j]; if(intersect(X,Y)>=k) { adj[i].push_back(j); adj[j].push_back(i); } } } int ans=0; for(int i=0;i<n;i++) { if(adj[i].size()>=0 && !visited[i]) { cout<<i<<endl; dfs(i); ans++; } } return ans; } }; ```
0
0
['C++']
0