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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
check-distances-between-same-letters | Not the best but just one-liner solution | not-the-best-but-just-one-liner-solution-6n25 | Code\n\n/**\n * @param {string} s\n * @param {number[]} distance\n * @return {boolean}\n */\nconst aCode = \'a\'.codePointAt(0);\nvar checkDistances = function( | ods967 | NORMAL | 2023-01-23T08:34:44.381759+00:00 | 2023-01-23T08:34:44.381804+00:00 | 99 | false | # Code\n```\n/**\n * @param {string} s\n * @param {number[]} distance\n * @return {boolean}\n */\nconst aCode = \'a\'.codePointAt(0);\nvar checkDistances = function(s, distance) {\n return [...s]\n .reduce((acc, char, i) => {\n acc[char.codePointAt(0) - aCode].push(i);\n return acc;\n }, Array(26).fill().map(() => []))\n .every((charIndicies, i) => {\n for (let j = 1; j < charIndicies.length; j++) {\n if (charIndicies[j] - charIndicies[j - 1] - 1 !== distance[i]) {\n return false;\n }\n }\n return true;\n });\n};\n``` | 1 | 0 | ['JavaScript'] | 0 |
check-distances-between-same-letters | c++ easy solution | c-easy-solution-by-ishita_jain-k160 | Code\n\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n map<char,int> m,temp;\n map<char,vector<int>> dist | ishita_jain | NORMAL | 2023-01-11T17:18:46.090197+00:00 | 2023-01-11T17:18:46.090242+00:00 | 74 | false | # Code\n```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n map<char,int> m,temp;\n map<char,vector<int>> dist;\n int ch=0;\n for(int i=0;i<distance.size();i++){\n m[\'a\'+ch]=distance[i];\n ch++;\n }\n for(int i=0;i<s.size();i++){\n dist[s[i]].push_back(i);\n }\n for(auto value:dist){\n temp[value.first]=(value.second[1]-value.second[0])-1;\n }\n map<char,int>::iterator it1 = m.begin();\n map<char,int>::iterator it2 = temp.begin();\n while(it2!=temp.end()){\n if(it1->first==it2->second){\n if(it1->second==it2->second){\n it1++;\n it2++;\n }\n else{\n return false;\n }\n }\n else{\n while(it1->first!=it2->first){\n it1++;\n }\n if(it1->second==it2->second){\n it1++;\n it2++;\n }\n else{\n return false;\n }\n }\n }\n return true;\n }\n};\n``` | 1 | 0 | ['Array', 'Hash Table', 'String', 'C++'] | 0 |
check-distances-between-same-letters | Kotlin O(n) no extra space used | kotlin-on-no-extra-space-used-by-c4tdog-cmhk | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | c4tdog | NORMAL | 2022-11-14T03:08:29.155252+00:00 | 2022-11-14T03:08:29.155292+00:00 | 44 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution {\n fun checkDistances(s: String, a: IntArray): Boolean {\n for (i in 0..s.length - 1) {\n var p = s[i].toInt() - 97\n if (a[p] >= 1000) {\n var prevPos = (a[p] / 1000) - 1\n var prevValue = a[p] - ((prevPos + 1) * 1000)\n if (i - prevPos - 1 != prevValue) return false\n } else {\n a[p] += (i + 1) * 1000 // remember position\n }\n }\n\n return true\n }\n}\n``` | 1 | 0 | ['Kotlin'] | 0 |
check-distances-between-same-letters | Java using lastIndexOf() | java-using-lastindexof-by-sebasolak-6qez | \n public static boolean checkDistances(String s, int[] distance) {\n\n for (int i = 0; i < s.length(); i++) {\n\n char c = s.charAt(i);\n | sebasolak | NORMAL | 2022-09-25T22:48:53.765863+00:00 | 2022-09-25T22:48:53.765897+00:00 | 199 | false | ```\n public static boolean checkDistances(String s, int[] distance) {\n\n for (int i = 0; i < s.length(); i++) {\n\n char c = s.charAt(i);\n int x = s.lastIndexOf(c);\n\n if (i != x) {\n int distanceValue = x - i - 1;\n if (distance[c - \'a\'] != distanceValue) return false;\n }\n \n }\n\n return true;\n }\n``` | 1 | 0 | ['Java'] | 0 |
check-distances-between-same-letters | Java Solution in 2 ms | No HashMap | O(N) | java-solution-in-2-ms-no-hashmap-on-by-t-t0dx | \n```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n boolean[] booleans = new boolean[26];\n for (int i = 0; i | tbekpro | NORMAL | 2022-09-24T13:00:51.333767+00:00 | 2022-09-24T13:00:51.333806+00:00 | 22 | false | \n```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n boolean[] booleans = new boolean[26];\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n int idx = i + distance[c - \'a\'] + 1;\n if (idx < s.length() && !booleans[c - \'a\'] && s.charAt(idx) != c || idx > s.length() - 1 && !booleans[c - \'a\']) {\n return false;\n } else {\n booleans[c - \'a\'] = true;\n }\n }\n return true;\n }\n} | 1 | 0 | [] | 0 |
check-distances-between-same-letters | Java Solution || ✓ 1ms runtime || faster than 99.87% | java-solution-1ms-runtime-faster-than-99-ywvn | Method 1\n\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n int[] list = new int[26];\n \n for(int i=0;i<s. | nishant7372 | NORMAL | 2022-09-24T05:28:39.702294+00:00 | 2022-09-24T05:44:34.132542+00:00 | 56 | false | ### *Method 1*\n```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n int[] list = new int[26];\n \n for(int i=0;i<s.length();i++)\n {\n if(list[s.charAt(i)-\'a\']==0)\n list[s.charAt(i)-\'a\']=i+1;\n\t\t\t\t\n else if(i-list[s.charAt(i)-\'a\']!=distance[s.charAt(i)-\'a\'])\n return false;\n }\n return true;\n }\n}\n```\n\n\n### *Method 2*\n```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n ArrayList<Integer>[] list = new ArrayList[26]; //can also use int[26][2]\n for(int i=0;i<26;i++)\n list[i] = new ArrayList<Integer>();\n \n for(int i=0;i<s.length();i++)\n {\n list[s.charAt(i)-\'a\'].add(i);\n }\n \n int i=0;\n for(ArrayList<Integer> temp: list)\n {\n if(temp.size()==2)\n {\n if(distance[i]!=(temp.get(1)-temp.get(0)-1))\n return false;\n }\n i++;\n }\n return true;\n }\n} | 1 | 0 | ['Hash Table'] | 0 |
check-distances-between-same-letters | NO EXTRA SPACE.. 100% Faster | EASY Solution | TC:O(N) : SC:O(1) | no-extra-space-100-faster-easy-solution-ha72i | \nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n for(int i = 0 ; i < s.length() ; i++){\n int dis = distanc | ashutoshbishttt | NORMAL | 2022-09-22T06:19:06.663467+00:00 | 2022-09-22T06:19:06.663509+00:00 | 142 | false | ```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n for(int i = 0 ; i < s.length() ; i++){\n int dis = distance[s.charAt(i)-\'a\'];\n if(i+dis+1<s.length() && s.charAt(i+dis+1)==s.charAt(i)){\n continue;\n }else if(i-dis-1>=0){\n if(s.charAt(i-dis-1)==s.charAt(i)){\n continue;\n }\n }else{\n return false;\n }\n }\n return true;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
check-distances-between-same-letters | Python | Easy Solution | 95% faster less than 47ms | python-easy-solution-95-faster-less-than-vo9t | \tclass Solution:\n\t\tdef checkDistances(self, s: str, distance: List[int]) -> bool:\n\n\t\t\tfor x in set(s):\n\t\t\t\tres=[i for i,k in enumerate(s) if k==x] | mdshahbaz204 | NORMAL | 2022-09-21T07:49:06.834019+00:00 | 2022-09-21T07:49:06.834058+00:00 | 186 | false | \tclass Solution:\n\t\tdef checkDistances(self, s: str, distance: List[int]) -> bool:\n\n\t\t\tfor x in set(s):\n\t\t\t\tres=[i for i,k in enumerate(s) if k==x]\n\t\t\t\tif res[1]-res[0]-1 != distance[ord(x)-97]:\n\t\t\t\t\treturn False\n\t\t\treturn True\n | 1 | 0 | ['Ordered Set', 'Python'] | 0 |
check-distances-between-same-letters | PHP 11ms | php-11ms-by-tarunjain28-5t7r | \n\n\nclass Solution {\n\n /**\n * @param String $s\n * @param Integer[] $distance\n * @return Boolean\n */\n function checkDistances($s, | tarunjain28 | NORMAL | 2022-09-20T13:24:54.372161+00:00 | 2022-09-20T13:24:54.372212+00:00 | 29 | false | \n\n```\nclass Solution {\n\n /**\n * @param String $s\n * @param Integer[] $distance\n * @return Boolean\n */\n function checkDistances($s, $distance) {\n $firstPos = array();\n $strParts = str_split($s);\n $matched = true;\n\n foreach($strParts as $key => $val) {\n if(!isset($firstPos[$val])) {\n $firstPos[$val] = $key;\n } else {\n $charDist = ($key - $firstPos[$val] - 1);\n $charIndex = ord($val) - 97;\n if($distance[$charIndex] != $charDist) {\n $matched = false;\n break;\n }\n }\n }\n\n return $matched;\n }\n}\n``` | 1 | 0 | ['PHP'] | 0 |
check-distances-between-same-letters | Python Solution | Easy Understanding | python-solution-easy-understanding-by-cy-nebm | \nclass Solution:\n def mapper(self, s): # finds difference of indices\n result = dict()\n for letter in set(s):\n indices = []\n | cyber_kazakh | NORMAL | 2022-09-19T10:43:15.705276+00:00 | 2022-09-19T10:43:15.705323+00:00 | 459 | false | ```\nclass Solution:\n def mapper(self, s): # finds difference of indices\n result = dict()\n for letter in set(s):\n indices = []\n for idx, value in enumerate(s):\n if value == letter:\n indices.append(idx)\n result[letter] = indices[1] - indices[0] - 1\n return result # dict like {\'a\':1, \'b\':0}\n\n def checkDistances(self, s, distance) -> bool:\n alphabet = \'abcdefghijklmnopqrstuvwxyz\'\n for key, value in self.mapper(s).items():\n if distance[alphabet.index(key)] != value:\n return False\n return True\n``` | 1 | 0 | ['Python', 'Python3'] | 0 |
check-distances-between-same-letters | Swift | One-Liner | swift-one-liner-by-upvotethispls-hjn5 | One-Liner, terse (accepted answer)\n\nclass Solution {\n func checkDistances(_ s: String, _ distance: [Int]) -> Bool {\n [Int:Int](s.enumerated().map | UpvoteThisPls | NORMAL | 2022-09-15T03:59:48.795500+00:00 | 2022-09-15T04:05:25.586166+00:00 | 36 | false | **One-Liner, terse (accepted answer)**\n```\nclass Solution {\n func checkDistances(_ s: String, _ distance: [Int]) -> Bool {\n [Int:Int](s.enumerated().map {(Int(exactly: $0.1.asciiValue!)!-97, $0.0)}, uniquingKeysWith: { abs($1-$0)-1 }).reduce(true) { $0 && distance[$1.0] == $1.1 }\n }\n}\n```\n**NOTE:** This is technically a one-liner, since the `return` keyword was omitted.\n\n---\n\n**One-Liner expanded and annotated (accepted answer)**\n```\nclass Solution {\n func checkDistances(_ s: String, _ distance: [Int]) -> Bool {\n // convert `s` to [Int], and map \'a\' ... \'z\' -> 0 ... 25\n let s = Array(s).map { Int(exactly: $0.asciiValue! - Character("a").asciiValue!)! }\n\n // create hashMap mapping letters (as Int) to distance between instances of letters\n let hashMap = [Int:Int](s.enumerated().map {($0.1, $0.0)}, uniquingKeysWith: { abs($1-$0)-1 })\n \n // compare all calculated distances with expected distances, return false if discrepancy found \n return hashMap.reduce(true) { result, tuple in\n let (letter, calculatedDistance) = tuple\n return result && distance[letter] == calculatedDistance \n }\n }\n}\n```\n\n---\n\n**For-loop, using Array for storage (accepted answer)**\n```\nclass Solution {\n func checkDistances(_ s: String, _ distance: [Int]) -> Bool {\n let s = Array(s).map { Int(exactly: $0.asciiValue! - Character("a").asciiValue!)! }\n var prev = Array(repeating: -1, count: 26)\n for (i, ch) in s.enumerated() {\n if prev[ch] < 0 {\n prev[ch] = i \n } else if distance[ch] != i - prev[ch] - 1 {\n return false\n }\n }\n return true\n }\n}\n```\n\n---\n\n**For-loop, using Hashmap for storage (accepted answer)**\n```\nclass Solution {\n func checkDistances(_ s: String, _ distance: [Int]) -> Bool {\n let s = Array(s).map { Int(exactly: $0.asciiValue! - Character("a").asciiValue!)! }\n var prev = [Int:Int]()\n for (i, ch) in s.enumerated() {\n if prev[ch] == nil {\n prev[ch] = i \n } else if distance[ch] != i - prev[ch]! - 1 {\n return false\n }\n }\n return true\n }\n}\n``` | 1 | 0 | [] | 0 |
check-distances-between-same-letters | C++ || 96% || O(N) || With Explanation | c-96-on-with-explanation-by-anas_parvez-ya8q | \nclass Solution\n{\n public:\n bool checkDistances(string s, vector<int> &distance)\n {\n \n //making use of set because don\'t | anas_parvez | NORMAL | 2022-09-13T14:57:21.109910+00:00 | 2022-09-13T14:57:21.109945+00:00 | 70 | false | ```\nclass Solution\n{\n public:\n bool checkDistances(string s, vector<int> &distance)\n {\n \n //making use of set because don\'t want to iterate already calculated results\n \n unordered_set<char>ch;\n for (int i = 0; i < s.size(); i++)\n {\n // i.e if the character is already been calculated earlier\n if(ch.find(s[i])!=ch.end()){\n continue;\n }\n \n // 1-condition - if the value of distance makes the size go out of bounds then false\n // 2-condition - check if the character is present at the location by adding the given distance+1\n // Here s[i]-\'a\' will give 0 if s[i] = a and 1 if s[i] = b and so on.\n \n if (distance[s[i] - \'a\'] + i + 1 > s.size() || s[i] != s[distance[s[i] - \'a\'] + i + 1]){\n return false;\n }\n \n //insert into the set because we calculated it and it was fine.\n \n else{\n ch.insert(s[i]); \n }\n }\n return true;\n }\n};\n``` | 1 | 0 | [] | 0 |
check-distances-between-same-letters | [C++] || Keep track of previous occurence | c-keep-track-of-previous-occurence-by-ra-t5i1 | \nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n vector<int> prev(26,-1) ; //stores the previous index of any ch | rahul921 | NORMAL | 2022-09-12T07:25:42.130955+00:00 | 2022-09-12T07:25:42.131309+00:00 | 35 | false | ```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n vector<int> prev(26,-1) ; //stores the previous index of any charater encountered\n for(int i = 0 ; i < s.size() ; ++i ){\n if(prev[s[i]-\'a\'] == -1) prev[s[i]-\'a\'] = i ;\n else if(distance[s[i]-\'a\'] != i - prev[s[i]-\'a\'] - 1) return false ;\n }\n return true ;\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
check-distances-between-same-letters | Java Solution | Array | Self Explanatory | java-solution-array-self-explanatory-by-tnvv3 | \n public boolean checkDistances(String s, int[] distance) {\n int[] freq = new int[26];\n Arrays.fill(freq, -1);\n \n for(int i= | anagda | NORMAL | 2022-09-10T03:47:54.449317+00:00 | 2022-09-10T03:47:54.449355+00:00 | 199 | false | ```\n public boolean checkDistances(String s, int[] distance) {\n int[] freq = new int[26];\n Arrays.fill(freq, -1);\n \n for(int i=0; i<s.length(); i++) {\n freq[s.charAt(i) - \'a\'] = i - freq[s.charAt(i) - \'a\']; \n }\n \n for(int i=0; i<s.length(); i++) {\n if(freq[s.charAt(i) - \'a\'] != -1 && freq[s.charAt(i) - \'a\'] != distance[s.charAt(i) - \'a\']) {\n return false;\n }\n }\n \n return true;\n }\n``` | 1 | 0 | ['Array', 'Java'] | 0 |
check-distances-between-same-letters | Python Solution | python-solution-by-vince100-277l | \nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n d = defaultdict(list)\n for i, c in enumerate(s):\n | vince100 | NORMAL | 2022-09-09T05:19:04.717265+00:00 | 2022-09-09T05:19:04.717307+00:00 | 69 | false | ```\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n d = defaultdict(list)\n for i, c in enumerate(s):\n d[c].append(i)\n return all(distance[ord(c) - ord("a")] == d[c][1] - d[c][0] - 1 for c in d)\n``` | 1 | 0 | [] | 1 |
check-distances-between-same-letters | O(n) single traversal Java solution | on-single-traversal-java-solution-by-muf-8bd4 | \nclass Solution {\n public boolean checkDistances(String s, int[] dist) {\n for (int i = 0; i < s.length(); i++) {\n int idx = s.charAt(i) | mufaddalhakim | NORMAL | 2022-09-08T14:29:12.568028+00:00 | 2022-09-08T14:29:12.568068+00:00 | 67 | false | ```\nclass Solution {\n public boolean checkDistances(String s, int[] dist) {\n for (int i = 0; i < s.length(); i++) {\n int idx = s.charAt(i) - 97;\n if (i + dist[idx]+1 < s.length() && s.charAt(i + dist[idx]+1) == s.charAt(i)) continue;\n else if (i - dist[idx]-1 >= 0 && s.charAt(i - dist[idx]-1) == s.charAt(i)) continue;\n else return false;\n }\n return true;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
check-distances-between-same-letters | ✅ JS | JavaScript | Easy to understand | js-javascript-easy-to-understand-by-pras-1bm2 | \n// Time complexity: O(n), where n is length of input string.\n// Space complexity: O(1)\n\nvar checkDistances = function(s, distance) {\n const firstIndex | prashantkachare | NORMAL | 2022-09-08T13:06:53.465496+00:00 | 2022-09-11T12:14:08.304333+00:00 | 367 | false | ```\n// Time complexity: O(n), where n is length of input string.\n// Space complexity: O(1)\n\nvar checkDistances = function(s, distance) {\n const firstIndex = Array(26).fill(-1);\n\t\n\tfor(let index = 0; index < s.length; index++) {\n\t\tconst charCode = s[index].charCodeAt(0) - \'a\'.charCodeAt(0);\n\t\t\n\t\tif(firstIndex[charCode] !== -1)\n\t\t\tif(index - firstIndex[charCode] - 1 !== distance[charCode])\n\t\t\t\treturn false;\n\t\t\n\t\tfirstIndex[charCode] = index;\n\t}\n\t\n\treturn true;\n};\n```\n\n**Please upvote if you find this solution useful. Happy Coding!** | 1 | 0 | ['JavaScript'] | 1 |
check-distances-between-same-letters | easy 1ms soln | easy-1ms-soln-by-ankit_parashar-x2g1 | HashMap hm = new HashMap<>();\n \n for(int i=0;i<s.length();i++)\n {\n char ch = s.charAt(i);\n if(hm.containsKey(ch) | ANKIT_PARASHAR | NORMAL | 2022-09-08T03:18:47.052196+00:00 | 2022-09-08T03:18:47.052233+00:00 | 17 | false | HashMap<Character,Integer> hm = new HashMap<>();\n \n for(int i=0;i<s.length();i++)\n {\n char ch = s.charAt(i);\n if(hm.containsKey(ch))\n {\n int diff = i-hm.get(ch)-1;\n int val = distance[ch-\'a\'];\n if(diff!=val)\n {\n return false;\n }\n }\n else\n {\n hm.put(ch,i);\n }\n }\n \n return true; | 1 | 0 | [] | 0 |
check-distances-between-same-letters | ✅C++ || 100% success || using unordered_map || Easy solution | c-100-success-using-unordered_map-easy-s-zhzk | Explanation: My intitution is by travesing the whole string , to store the initial occurance of the element in unordered_map if the elment is not present in the | Jeevalok | NORMAL | 2022-09-05T14:12:20.075912+00:00 | 2022-09-05T14:12:20.075956+00:00 | 46 | false | **Explanation**: My intitution is by travesing the whole string , to store the initial occurance of the element in ```unordered_map``` if the elment is not present in the map, otherwise check if the distance between the 1st & 2nd occurances of the element is **equal** or **not** with the distance of element in given vector.\n\n**Code :**\n\n```\n\t\tclass Solution {\n\t\t\tpublic:\n\t\t\t\tbool checkDistances(string s, vector<int>& distance) {\n\t\t\t\t\tunordered_map<char,int> mp;\n\t\t\t\t\tfor(int i=0;i<s.length();i++){\n\t\t\t\t\t\tif(mp.find(s[i])==mp.end()){\n\t\t\t\t\t\t\tmp[s[i]]=i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tif((i-mp[s[i]]-1) != distance[s[i]-\'a\']) return false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t};\n```\n | 1 | 0 | ['C++'] | 0 |
check-distances-between-same-letters | Java || HashMap || Easy | java-hashmap-easy-by-siddu6003-766f | \nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n Map<Character,Integer> m = new HashMap<>();\n \n for(in | siddu6003 | NORMAL | 2022-09-05T06:08:40.145726+00:00 | 2022-09-05T06:08:40.145765+00:00 | 78 | false | ```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n Map<Character,Integer> m = new HashMap<>();\n \n for(int i=0;i<s.length();i++){\n if(m.containsKey(s.charAt(i))){\n if(i-m.get(s.charAt(i))-1!=distance[s.charAt(i)-\'a\']) return false;\n }else{\n m.put(s.charAt(i),i);\n }\n }\n return true;\n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
check-distances-between-same-letters | O(n) || 100% faster || Easy Solution | on-100-faster-easy-solution-by-tilak_ban-fcmf | \nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n vector<int> A(26,0);\n vector<int> B(26,0);\n for | tilak_bang | NORMAL | 2022-09-04T13:35:46.152763+00:00 | 2022-09-04T13:35:46.152801+00:00 | 36 | false | ```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n vector<int> A(26,0);\n vector<int> B(26,0);\n for(int i=0;i<s.size();i++){\n if(A[s[i]-\'a\']!=0){\n B[s[i]-\'a\']=i+1;\n }\n else{\n A[s[i]-\'a\']=i+1;\n }\n }\n for(int i=0;i<26;i++){\n if((B[i]-A[i])!=0){\n if((B[i]-A[i]-1)!=distance[i]){\n return false;\n }\n }\n }\n return true;\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
check-distances-between-same-letters | Rust solution | rust-solution-by-bigmih-3dlm | \nimpl Solution {\n pub fn check_distances(s: String, mut distance: Vec<i32>) -> bool {\n for (b, pos) in s.bytes().zip(0..) {\n let dist = | BigMih | NORMAL | 2022-09-04T12:47:48.813347+00:00 | 2022-09-04T12:47:48.813394+00:00 | 57 | false | ```\nimpl Solution {\n pub fn check_distances(s: String, mut distance: Vec<i32>) -> bool {\n for (b, pos) in s.bytes().zip(0..) {\n let dist = &mut distance[(b - b\'a\') as usize];\n match *dist >= 0 {\n true => *dist = -(*dist + pos + 1), // set next pos with negative flag\n false if *dist != -pos => return false, // check wrong distance\n _ => (),\n }\n }\n true\n }\n}\n``` | 1 | 0 | ['Rust'] | 1 |
check-distances-between-same-letters | C++ Easy Solution | c-easy-solution-by-kartikdangi01-rtdi | \nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n vector<bool> vis(26,false);\n int n = s.size();\n | kartikdangi01 | NORMAL | 2022-09-04T09:12:33.171195+00:00 | 2022-09-04T09:12:33.171241+00:00 | 42 | false | ```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n vector<bool> vis(26,false);\n int n = s.size();\n for(int i=0;i<n;i++){\n if(vis[s[i]-\'a\']) continue;\n if(i+distance[s[i]-\'a\']+1<n && s[i+distance[s[i]-\'a\']+1]==s[i]){\n vis[s[i]-\'a\']=true; continue;\n }\n else\n return false;\n }\n return true;\n }\n};\n``` | 1 | 0 | ['C', 'C++'] | 0 |
check-distances-between-same-letters | 100.00% of c++ || Beginner friendly || Without using hashmap || O(1) space complexity | 10000-of-c-beginner-friendly-without-usi-qfa9 | If you really found my solution helpful please upvote it, as it motivates me, if you have some queries or some improvements please feel free to comment and shar | Akash-Jha | NORMAL | 2022-09-04T07:46:20.382137+00:00 | 2022-09-04T07:46:20.382165+00:00 | 32 | false | **If you really found my solution helpful please upvote it, as it motivates me, if you have some queries or some improvements please feel free to comment and share your views.**\n\n```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n \n int n = s.size();\n for(int i=0;i<n;i++){\n \n if(s[i]!=\'A\'){\n char c = s[i];\n size_t f = s.find(c , i+1);\n \n if(distance[s[i]-\'a\']==(f-i-1)){\n s[f]=\'A\';\n j++;\n }\n else{\n return false;\n }\n }\n }\n \n return true;\n }\n};\n``` | 1 | 0 | ['C'] | 1 |
check-distances-between-same-letters | Simple C++ bruteforce||100% fast | simple-c-bruteforce100-fast-by-goku_sama-r06q | \nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& d) {\n map<char,vector<int>> m;\n for(int i=0;i<s.length();i++){\n | goku_sama | NORMAL | 2022-09-04T07:43:40.100455+00:00 | 2022-09-04T07:45:54.715188+00:00 | 45 | false | ```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& d) {\n map<char,vector<int>> m;\n for(int i=0;i<s.length();i++){\n m[s[i]].push_back(i);\n } \n for(auto it:m){\n int u = it.second[0],v=it.second[1];\n int a = d[it.first - \'a\'];\n if(a != v-u-1 ) return 0;\n }\n return 1;\n }\n};\n``` | 1 | 0 | ['C', 'C++'] | 0 |
check-distances-between-same-letters | Java solution | Two approaches | java-solution-two-approaches-by-sourin_b-yn2r | Please Upvote !!!\n\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n int[] arr = new int[26];\n Arrays.fill(arr, | sourin_bruh | NORMAL | 2022-09-04T07:24:41.160040+00:00 | 2022-09-04T07:24:41.160081+00:00 | 18 | false | ### **Please Upvote !!!**\n```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n int[] arr = new int[26];\n Arrays.fill(arr, -1);\n\n for (int i = 0; i < s.length(); i++) {\n int index = s.charAt(i) - \'a\';\n int inBetween = i - arr[index] - 1;\n if (arr[index] > -1 && inBetween != distance[index]) return false;\n arr[index] = i;\n }\n\n return true;\n }\n}\n\n// TC: O(n), SC: O(1)\n\n// -----------------------------------------------------------------------------------\n\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n int firstIdx = s.indexOf(c);\n int lastIdx = s.lastIndexOf(c);\n int inBetween = lastIdx - firstIdx - 1;\n if (inBetween != distance[c - \'a\']) return false;\n }\n\n return true;\n }\n}\n\n// TC: O(n), SC: O(1)\n``` | 1 | 0 | ['Java'] | 0 |
check-distances-between-same-letters | Python simple and efficient solution. | python-simple-and-efficient-solution-by-xjwhz | Time - complexity = O(n)\nSpace complexity = O(1)\n```\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n \n d | MaverickEyedea | NORMAL | 2022-09-04T05:57:14.499819+00:00 | 2022-09-04T05:57:14.499857+00:00 | 60 | false | Time - complexity = O(n)\nSpace complexity = O(1)\n```\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n \n dist = [-1] * (len(distance))\n \n n = len(s)\n \n for i in range(n):\n index = ord(s[i]) - ord(\'a\')\n \n if dist[index] == -1:\n dist[index] = i\n else:\n if distance[index] != (i - dist[index] - 1):\n return False\n \n return True\n \n | 1 | 0 | ['Python'] | 0 |
check-distances-between-same-letters | 100% Faster [JS / Python] Solutions | 100-faster-js-python-solutions-by-priyan-g9ct | \n# Python Solution\n# TC - O(n), SC - (1)\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n n = len(distance)\n | priyanka1719 | NORMAL | 2022-09-04T05:00:41.720176+00:00 | 2022-09-04T05:00:41.720229+00:00 | 184 | false | ```\n# Python Solution\n# TC - O(n), SC - (1)\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n n = len(distance)\n arr = [-1]*n\n m = len(s)\n for i in range(m):\n index = ord(s[i]) - ord(\'a\')\n if(arr[index] == -1):\n arr[index] = i\n else:\n dist = i - (arr[index] + 1)\n arr[index] = dist\n if(arr[index] != distance[index]):\n return False\n return True\n \n```\n```\n// JS Solution\n/ / TC - O(n), SC - (1)\n/**\n * @param {string} s\n * @param {number[]} distance\n * @return {boolean}\n */\nvar checkDistances = function(s, distance) {\n n = s.length\n const arr = new Array(distance.length).fill(-1)\n // console.log(arr)\n for(let i=0; i<n; i++){\n const index = s[i].charCodeAt() - \'a\'.charCodeAt()\n if(arr[index] == -1){\n arr[index] = i\n } else {\n dist = i - (arr[index] + 1)\n arr[index] = dist\n if(arr[index] != distance[index]){\n return false\n }\n }\n }\n return true\n};\n```\n\n | 1 | 1 | ['Python', 'JavaScript'] | 1 |
check-distances-between-same-letters | Easy solution, Ascii value logic | easy-solution-ascii-value-logic-by-sundr-jrta | \nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n hashmap=dict()\n for i in range(len(s)):\n if o | sundram_somnath | NORMAL | 2022-09-04T04:59:48.103566+00:00 | 2022-09-04T04:59:48.103608+00:00 | 16 | false | ```\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n hashmap=dict()\n for i in range(len(s)):\n if ord(s[i]) not in hashmap:\n hashmap[ord(s[i])]=[i]\n else:\n hashmap[ord(s[i])].append(i)\n \n \n for i in hashmap:\n if hashmap[i][1]-hashmap[i][0]-1!=distance[i-97]:\n return False\n return True\n \n``` | 1 | 0 | [] | 0 |
check-distances-between-same-letters | ✅ C++ Unordered Map Hindi Video Explanation | c-unordered-map-hindi-video-explanation-dxb0f | It can be solved using unordered map for storing index of character last seen\nC++ Code and Hindi Video explanation in case anyone\'s interested.\nhttps://youtu | Leetcode_Hindi | NORMAL | 2022-09-04T04:49:53.334310+00:00 | 2022-09-04T04:49:53.334346+00:00 | 31 | false | It can be solved using unordered map for storing index of character last seen\nC++ Code and Hindi Video explanation in case anyone\'s interested.\nhttps://youtu.be/0_TdytWLHfE\n\n```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n vector<int> char_index(26, -1);\n int n = s.size();\n for (int i = 0; i < n; ++i) {\n int current_char = s[i] - \'a\';\n if (char_index[current_char] != -1 && i - char_index[current_char]-1 != distance[current_char]) {\n return false;\n }\n char_index[current_char] = i;\n }\n return true;\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
check-distances-between-same-letters | Rust | Map | With Comments | rust-map-with-comments-by-wallicent-6hky | EDIT 2022-09-04: I had to come back and do a nicer solution with the excellent tips from BigMih regarding .zip(0..) and .bytes(). Thanks!\n\n\nimpl Solution {\n | wallicent | NORMAL | 2022-09-04T04:43:17.581874+00:00 | 2022-09-04T18:14:31.763140+00:00 | 36 | false | EDIT 2022-09-04: I had to come back and do a nicer solution with the excellent tips from [BigMih](https://leetcode.com/BigMih/) regarding `.zip(0..)` and `.bytes()`. Thanks!\n\n```\nimpl Solution {\n pub fn check_distances(s: String, distance: Vec<i32>) -> bool {\n (0..).zip(s.bytes()).scan(vec![-1; 26], |v, (i, c)| {\n match &mut v[(c - b\'a\') as usize] {\n entry @ &mut -1 => {\n *entry = i;\n Some(true)\n },\n entry => Some(*entry == i - distance[(c - b\'a\') as usize]),\n }\n }).all(|b| b)\n }\n}\n```\n\n**Original Post**\n\nThis is my unaltered submission for the 2022-09-04 Weekly Contest 309. I record the first and last occurrence of each letter. I used the sentinel -1 here to signal that we didn\'t encounter the letter in question. Then I just check that the recorded distances of the encountered letters match those in `distance`.\n\nTime: O(n)\nSpace: O(n)\n\nComments: My second contest. I tried to code faster and do less of "clean and functional-style", so this solution was in line with my goals. :)\n\n```\nimpl Solution {\n pub fn check_distances(s: String, distance: Vec<i32>) -> bool {\n let mut map = vec![(-1, -1); 26];\n for (i, c) in s.as_bytes().iter().enumerate() {\n let entry = &mut map[(*c - b\'a\') as usize];\n if entry.0 == -1 {\n entry.0 = i as i32;\n } else {\n entry.1 = i as i32;\n }\n }\n map.into_iter().enumerate().all(|(i, (first, second))| first == -1 || second - first - 1 == distance[i])\n }\n}\n``` | 1 | 0 | ['Rust'] | 1 |
determine-if-two-strings-are-close | [ C++ ] Short and Simple || O( N ) solution | c-short-and-simple-o-n-solution-by-suman-s5xu | Idea : Two thing\'s Need to check \n1. Frequency of Char need\'s to be same there both of string as we can do Transform every occurrence of one existing charact | suman_buie | NORMAL | 2020-11-15T04:00:45.410952+00:00 | 2020-12-04T07:57:26.046973+00:00 | 27,317 | false | **Idea :** Two thing\'s Need to check \n1. Frequency of Char need\'s to be same there both of string as we can do **Transform every occurrence of one existing character into another existing character**\n2. All the unique char which there in String1 need\'s to there as well In string2 \n\n**let\'s See One example :** \n```\nString 1 = "aabaacczp" String 2="bbzbbaacp"\nFrequency in string1 : Frequency in string2 :\n\t a->4 b->4\n\t\tb->1 a->2\n\t\tc->2 z->1\n\t\tz->1 c->1\n\t\tp->1 p->1\n\t\t\nsee in String 1 count array -> 1, 1, 1, 2, 4 =>sorted order\nand in String 2 count array -> 1, 1, 1, 2, 4 =>sorted order\n\nUnique all char a,b,c,z,p in string 1 is there as well in string2 so it\'s a valid One just return True\n\n```\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n vector<int>w1(26,0),w2(26,0);\n set<char>s1,s2;\n for(char c:word1){\n w1[c-\'a\']++;\n s1.insert(c);\n }\n for(char c:word2){\n w2[c-\'a\']++;\n s2.insert(c);\n }\n sort(begin(w1),end(w1));\n sort(begin(w2),end(w2));\n return w1==w2&&s1==s2;\n }\n};\n```\n**One Improvemnt :**\nInsted of use set we can Use normal array to reduce time complexcity into **O(Nlog N) to O(N)**\nFallowing the improve code\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n vector<int>w1(26,0),w2(26,0),w3(26,0),w4(26,0);\n for(char c:word1)\n w1[c-\'a\']++,w3[c-\'a\'] = 1;\n \n for(char c:word2)\n w2[c-\'a\']++,w4[c-\'a\'] = 1;\n \n sort(begin(w1),end(w1));\n sort(begin(w2),end(w2));\n return w1==w2&&w3==w4;\n }\n};\n```\nAny doubt ask There\nFor help please **Upvote**\n**Thank You :)** | 327 | 3 | [] | 54 |
determine-if-two-strings-are-close | ✅☑Beats 99.46% Users || [C++/Java/Python/JavaScript] || EXPLAINED🔥 | beats-9946-users-cjavapythonjavascript-e-kp98 | PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n\n---\n\n# Approaches\n(Also explained in the code)\n\n1. Frequency Counting:\n\n - Two vectors (freq1 and freq2) are | MarkSPhilip31 | NORMAL | 2024-01-14T00:08:49.795846+00:00 | 2024-01-14T10:18:19.817719+00:00 | 55,893 | false | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n\n---\n\n# Approaches\n(Also explained in the code)\n\n1. **Frequency Counting:**\n\n - Two vectors (`freq1` and `freq2`) are used to count the frequency of each letter in `word1` and `word2`.\n - `freq1[i]` stores the count of the i-th letter in the English alphabet in `word1`, and similarly for `freq2`.\n1. **Checking Presence of Characters:**\n\n - Iterate over each character in the alphabet.\n - If a character is present in one word and not in the other (or vice versa), return `false`.\n - This ensures that both words contain the same set of characters.\n1. **Sorting Frequencies:**\n\n - Sort the frequency vectors (`freq1` and `freq2`).\n - This step is necessary because the order of frequencies doesn\'t matter, only their values.\n1. **Comparing Sorted Frequencies:**\n\n - Iterate through the sorted frequency vectors and compare corresponding elements.\n - If any corresponding elements are not equal, return `false`.\n1. **Final Result:**\n\n - If all the checks pass, return `true`, indicating that the two words are "close" as per the problem definition.\n\n\n\n# Complexity\n- Time complexity:\n $$O(n)$$\n*(Sorting on a constant Array (n=26) does not affect the time complexity of the algorithm)*\n \n\n- Space complexity:\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n bool closeStrings(std::string word1, std::string word2) {\n std::vector<int> freq1(26, 0);\n std::vector<int> freq2(26, 0);\n\n for (char ch : word1) {\n freq1[ch - \'a\']++;\n }\n\n for (char ch : word2) {\n freq2[ch - \'a\']++;\n }\n\n for (int i = 0; i < 26; i++) {\n if ((freq1[i] == 0 && freq2[i] != 0) || (freq1[i] != 0 && freq2[i] == 0)) {\n return false;\n }\n }\n\n std::sort(freq1.begin(), freq1.end());\n std::sort(freq2.begin(), freq2.end());\n\n for (int i = 0; i < 26; i++) {\n if (freq1[i] != freq2[i]) {\n return false;\n }\n }\n\n return true;\n }\n};\n\n\n\n\n```\n```Java []\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n int[] freq1 = new int[26];\n int[] freq2 = new int[26];\n\n for (char ch : word1.toCharArray()) {\n freq1[ch - \'a\']++;\n }\n\n for (char ch : word2.toCharArray()) {\n freq2[ch - \'a\']++;\n }\n\n for (int i = 0; i < 26; i++) {\n if ((freq1[i] == 0 && freq2[i] != 0) || (freq1[i] != 0 && freq2[i] == 0)) {\n return false;\n }\n }\n\n Arrays.sort(freq1);\n Arrays.sort(freq2);\n\n for (int i = 0; i < 26; i++) {\n if (freq1[i] != freq2[i]) {\n return false;\n }\n }\n\n return true;\n }\n}\n\n\n```\n```python3 []\n\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n freq1 = [0] * 26\n freq2 = [0] * 26\n\n for ch in word1:\n freq1[ord(ch) - ord(\'a\')] += 1\n\n for ch in word2:\n freq2[ord(ch) - ord(\'a\')] += 1\n\n for i in range(26):\n if (freq1[i] == 0 and freq2[i] != 0) or (freq1[i] != 0 and freq2[i] == 0):\n return False\n\n freq1.sort()\n freq2.sort()\n\n for i in range(26):\n if freq1[i] != freq2[i]:\n return False\n\n return True\n\n\n```\n```javascript []\nvar closeStrings = function(word1, word2) {\n let freq1 = new Array(26).fill(0);\n let freq2 = new Array(26).fill(0);\n\n for (let ch of word1) {\n freq1[ch.charCodeAt(0) - \'a\'.charCodeAt(0)]++;\n }\n\n for (let ch of word2) {\n freq2[ch.charCodeAt(0) - \'a\'.charCodeAt(0)]++;\n }\n\n for (let i = 0; i < 26; i++) {\n if ((freq1[i] === 0 && freq2[i] !== 0) || (freq1[i] !== 0 && freq2[i] === 0)) {\n return false;\n }\n }\n\n freq1.sort((a, b) => a - b);\n freq2.sort((a, b) => a - b);\n\n for (let i = 0; i < 26; i++) {\n if (freq1[i] !== freq2[i]) {\n return false;\n }\n }\n\n return true;\n};\n\n\n```\n\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n--- | 290 | 6 | ['Hash Table', 'String', 'Sorting', 'Counting', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 26 |
determine-if-two-strings-are-close | [Python] Oneliner with Counter, explained | python-oneliner-with-counter-explained-b-utmr | Let us look more carefully at this problem:\n1. Operation 1 allows us to swap any two symbols, so what matters in the end not order of them, but how many of eac | dbabichev | NORMAL | 2021-01-22T08:16:55.926857+00:00 | 2021-01-22T08:16:55.926900+00:00 | 9,316 | false | Let us look more carefully at this problem:\n1. Operation 1 allows us to swap any two symbols, so what matters in the end not order of them, but how many of each symbol we have. Imagine we have `(6, 3, 3, 5, 6, 6)` frequencies of symbols, than we need to have the same frequencies for the second string as well. So, we need to check if we have the same elements, but in different order (that is one is anagramm of another), how we can efficiently check it? We can sort both of them and compare, or we can use Counter again to check if these two lists have the same elements! Yes, we use here Counter of Counter and to be honest I see it first time, but it is not that diffucult.\n2. Operation 2 allows us to rename our letters, but we need to use the same letters: it means, that set of letters in first and second strings should be the same.\n\n**Complexity**: time complexity is `O(n)`: we create counters, and then again create counters. Space complexity is `O(m)`, where `m` is size of alphabet to keep our counters.\n\n```\nclass Solution:\n def closeStrings(self, w1, w2):\n return set(w1) == set(w2) and Counter(Counter(w1).values()) == Counter(Counter(w2).values())\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 130 | 11 | [] | 18 |
determine-if-two-strings-are-close | ✅ C++ || EASY || DETAILED EXPLAINATION || O(N) | c-easy-detailed-explaination-on-by-ayush-u51o | PLEASE UPVOTE IF YOU FIND MY APPROACH HELPFUL, MEANS A LOT \uD83D\uDE0A\n\nIntuition: We just have to check for size and frequency\n\nApproach:\n condition1 : w | ayushsenapati123 | NORMAL | 2022-12-02T02:52:12.166775+00:00 | 2022-12-02T02:52:12.166808+00:00 | 7,753 | false | **PLEASE UPVOTE IF YOU FIND MY APPROACH HELPFUL, MEANS A LOT \uD83D\uDE0A**\n\n**Intuition:** We just have to check for size and frequency\n\n**Approach:**\n* *condition1* : we need the size of both strings to be same\n* *condition2* : we need freq of char in strings to be same, irrespective of the order\n\n If above 2 conditions are satisfied then just swapping will get us the word2 from word1\n \n ```\n class Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n // condition1 : we need the size of both strings to be same\n // condition2 : we need freq of char in strings to be same, irrespective of the order\n // if above 2 conditions are satisfied then just swapping will get us the word2 from word1\n \n if(word1.size()!=word2.size())\n return false;\n \n set<char> s1, s2;\n vector<int> freq1(26,0), freq2(26,0);\n \n for(int i=0; i<word1.size(); i++)\n {\n s1.insert(word1[i]);\n s2.insert(word2[i]);\n \n freq1[word1[i] - \'a\']++;\n freq2[word2[i] - \'a\']++;\n }\n \n sort(freq1.begin(), freq1.end());\n sort(freq2.begin(), freq2.end());\n \n if(s1==s2 && freq1==freq2)\n return true;\n else\n return false; \n }\n};\n ```\n \n**Time Complexity** : `O(n)`\n\n\n | 100 | 10 | ['C++'] | 14 |
determine-if-two-strings-are-close | ✅Beats 100% - C++/Java/Python/JS - Explained with [ Video ] - Hash - Sort - Count | beats-100-cjavapythonjs-explained-with-v-fiy9 | \n\n# YouTube Video Explanation:\n\n **If you want a video for this question please write in the comments** \n\n https://www.youtube.com/watch?v=ujU-jeO1v-k \n\ | lancertech6 | NORMAL | 2024-01-14T02:58:31.834330+00:00 | 2024-01-14T04:05:36.096072+00:00 | 14,313 | false | \n\n# YouTube Video Explanation:\n\n<!-- **If you want a video for this question please write in the comments** -->\n\n<!-- https://www.youtube.com/watch?v=ujU-jeO1v-k -->\n\nhttps://youtu.be/wCnJIPGSXS4\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: https://www.youtube.com/@leetlogics/?sub_confirmation=1\n\n*Subscribe Goal: 1500 Subscribers*\n*Current Subscribers: 1403*\n\n---\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve this problem, we need to understand that the operations allowed don\'t change the frequency of characters, only their positions or representations. Therefore, two "close" strings must have the same set of characters and the same frequency of each character, although the characters themselves can be different.\n\nThe crucial realization is that operation 1 allows us to reorder characters in any fashion, making the relative order of characters inconsequential. Operation 2 allows us to transform characters into each other, given that both characters exist in both strings. The consequence of this is:\n\n- Both word1 and word2 must contain the same unique characters - they must have the same set of keys in their character counts (Counter).\n- Both word1 and word2 must have the same character frequencies, which implies, after sorting their frequency counts, these should match.\n\nIf both the sorted values of the counts and the sets of unique characters match, we return true. Otherwise, we return false.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe solution takes the following approach:\n\n1. Use Python\'s `Counter` from the collections module to count the frequency of each character in both `word1` and `word2`. Counter is a dictionary subclass that\'s designed to count hashable objects. It\'s a collection where elements are stored as dictionary keys and their counts are stored as dictionary values.\n\n2. Check if the set of keys from both Counters is the same\u2014`set(cnt1.keys()) == set(cnt2.keys())`. This checks whether word1 and word2 contain exactly the same unique characters. This is a requirement because operation 2 can only be performed if a character exists in both strings.\n\n3. Compare the sorted values of both counters\u2014`sorted(cnt1.values()) == sorted(cnt2.values())`. This step checks if `word1` and `word2` have the same frequency of characters (the same count of each character). Sorting is crucial here since we need to compare frequencies regardless of the character they are associated with.\n\nIf both conditions are met, then `word1` and `word2` are "close", and the function returns `True`. If any of the conditions is not met, the function returns `False`. These comparisons effectively implement the constraints of the two operations without having to manually perform the operations themselves.\n\n# Complexity\n- Time complexity: Considering the most expensive operations, the overall time complexity is `O(NlogN + MlogM)`, since the logarithmic factors in sorting dominates the linear factors from other operations.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: The overall space complexity is `O(N + M)`, which accounts for the storage of the character counts and the unique characters.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n int[] freq1 = new int[26];\n int[] freq2 = new int[26];\n\n for (int i = 0; i < word1.length(); ++i) {\n freq1[word1.charAt(i) - \'a\']++;\n }\n\n for (int i = 0; i < word2.length(); ++i) {\n freq2[word2.charAt(i) - \'a\']++;\n }\n\n for (int i = 0; i < 26; ++i) {\n if ((freq1[i] > 0 && freq2[i] == 0) || (freq2[i] > 0 && freq1[i] == 0)) {\n return false; \n }\n }\n\n Arrays.sort(freq1);\n Arrays.sort(freq2);\n\n for (int i = 0; i < 26; ++i) {\n if (freq1[i] != freq2[i]) {\n return false; \n }\n }\n return true;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n bool closeStrings(std::string word1, std::string word2) {\n std::array<int, 26> charCount1 = {}; \n std::array<int, 26> charCount2 = {}; \n for (char c : word1) {\n ++charCount1[c - \'a\'];\n }\n\n for (char c : word2) {\n ++charCount2[c - \'a\'];\n }\n\n for (int i = 0; i < 26; ++i) {\n bool charPresentWord1 = charCount1[i] > 0;\n bool charPresentWord2 = charCount2[i] > 0;\n\n if ((charPresentWord1 && !charPresentWord2) || (!charPresentWord1 && charPresentWord2)) {\n return false;\n }\n }\n\n std::sort(charCount1.begin(), charCount1.end());\n std::sort(charCount2.begin(), charCount2.end());\n\n for (int i = 0; i < 26; ++i) {\n if (charCount1[i] != charCount2[i]) {\n return false;\n }\n }\n\n return true;\n }\n};\n```\n```Python []\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n frequency_word1 = Counter(word1)\n frequency_word2 = Counter(word2)\n\n sorted_values_word1 = sorted(frequency_word1.values())\n sorted_values_word2 = sorted(frequency_word2.values())\n \n keys_match = set(frequency_word1.keys()) == set(frequency_word2.keys())\n\n return sorted_values_word1 == sorted_values_word2 and keys_match\n```\n```JavaScript []\n/**\n * @param {string} word1\n * @param {string} word2\n * @return {boolean}\n */\nvar closeStrings = function(word1, word2) {\n const freq1 = new Array(26).fill(0);\n const freq2 = new Array(26).fill(0);\n\n for (let i = 0; i < word1.length; ++i) {\n freq1[word1.charCodeAt(i) - \'a\'.charCodeAt(0)]++;\n }\n\n for (let i = 0; i < word2.length; ++i) {\n freq2[word2.charCodeAt(i) - \'a\'.charCodeAt(0)]++;\n }\n\n for (let i = 0; i < 26; ++i) {\n if ((freq1[i] > 0 && freq2[i] === 0) || (freq2[i] > 0 && freq1[i] === 0)) {\n return false;\n }\n }\n\n freq1.sort((a, b) => a - b);\n freq2.sort((a, b) => a - b);\n\n for (let i = 0; i < 26; ++i) {\n if (freq1[i] !== freq2[i]) {\n return false;\n }\n }\n\n return true;\n};\n```\n\n | 77 | 8 | ['Hash Table', 'String', 'Sorting', 'Counting', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 11 |
determine-if-two-strings-are-close | [Java] O(n) solution. | java-on-solution-by-lincanshu-zhu0 | java\nclass Solution {\n private int N = 26;\n public boolean closeStrings(String word1, String word2) {\n\t\t// count the English letters\n int[] | lincanshu | NORMAL | 2020-11-15T04:00:43.476478+00:00 | 2020-11-15T04:10:24.299340+00:00 | 12,281 | false | ```java\nclass Solution {\n private int N = 26;\n public boolean closeStrings(String word1, String word2) {\n\t\t// count the English letters\n int[] arr1 = new int[N], arr2 = new int[N];\n for (char ch : word1.toCharArray())\n arr1[ch - \'a\']++;\n for (char ch : word2.toCharArray())\n arr2[ch - \'a\']++;\n\t\t\n\t\t// if one has a letter which another one doesn\'t have, dont exist\n for (int i = 0; i < N; i++) {\n if (arr1[i] == arr2[i]) {\n continue;\n }\n if (arr1[i] == 0 || arr2[i] == 0) {\n return false;\n }\n }\n Arrays.sort(arr1);\n Arrays.sort(arr2);\n for (int i = 0; i < N; i++) {\n if (arr1[i] != arr2[i]) {\n return false;\n }\n }\n return true;\n }\n}\n``` | 71 | 2 | ['Java'] | 13 |
determine-if-two-strings-are-close | ✅ [Python/C++] O(N) one-liner + PROOF (explained) | pythonc-on-one-liner-proof-explained-by-4f77e | \u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.\n*\nThis solution employs counting of frequencies and comparison of unique characters in both strings. Time com | stanislav-iablokov | NORMAL | 2022-12-02T00:38:24.237661+00:00 | 2022-12-02T02:37:28.603586+00:00 | 4,352 | false | **\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n****\nThis solution employs counting of frequencies and comparison of unique characters in both strings. Time complexity is linear: **O(N)**. Space complexity is linear: **O(N)**.\n****\n\n**Comment.** The idea behind this solution consists in considering its invariants (i.e., properties that do not change after either of 2 operations was applied):\n1. New (unique) characters can not appear, neither can old ones be completely eliminated.\n2. Character frequencies can not be altered, they can only be arbitrarily redistributed (permuted) between existing characters.\n\nThis leads to a simple solution that consists in\n1. Checking that unique characters in both strings coincide.\n2. Checking that collections of character frequencies in both strings coincide.\n\n**Proof.** It is always possible to redistribute frequencies between two equal sets of characters due to a known theorem stating that *any permutation can be written as a product of transpositions (swaps)*. Thus, if for any two words the conditions that we check above are satisified then one word can always be attained from the other.\n\n**Python #1.** Comparison of sorted frequencies.\n```\nclass Solution:\n def closeStrings(self, w1: str, w2: str) -> bool:\n return sorted(Counter(w1).values()) == sorted(Counter(w2).values()) \\\n and set(w1) == set(w2)\n```\n\n**Python #2.** Double-counting of frequencies.\n```\nclass Solution:\n def closeStrings(self, w1: str, w2: str) -> bool:\n return Counter(Counter(w1).values()) == Counter(Counter(w2).values()) \\\n and set(w1) == set(w2)\n```\n\n**C++.** \n```\nclass Solution \n{\npublic:\n bool closeStrings(string w1, string w2) \n {\n vector<int> f1(26), f2(26);\n for (char c : w1) ++f1[c-\'a\'];\n for (char c : w2) ++f2[c-\'a\'];\n \n return multiset(f1.begin(),f1.end()) == multiset(f2.begin(),f2.end()) &&\n unordered_set(w1.begin(),w1.end()) == unordered_set(w2.begin(),w2.end());\n }\n};\n``` | 63 | 2 | [] | 15 |
determine-if-two-strings-are-close | [Java/Python3] 1-line Python3 Solution beat 100%!!! Check this out. | javapython3-1-line-python3-solution-beat-ksua | To solve this problem, we can find that if 2 strings have same unique characters and the value patterns are same, then we can return true. \n\nPython3 more Effi | admin007 | NORMAL | 2020-11-15T04:32:26.314892+00:00 | 2020-11-15T07:43:09.936040+00:00 | 8,137 | false | To solve this problem, we can find that if 2 strings have same unique characters and the value patterns are same, then we can return true. \n\n**Python3 more Efficient 1-line Solution (inspired by Chumicat):**\n\n```\nfrom collections import Counter\n\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n return set(word1) == set(word2) and Counter(Counter(word1).values()) == Counter(Counter(word2).values())\n```\n\n**My Original Python 1-line Solution:**\n\n```\nfrom collections import Counter\n\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n return sorted(Counter(word1).values()) == sorted(Counter(word2).values()) and set(Counter(word1).keys()) == set(Counter(word2).keys())\n```\n\n**Java Straightforward Solution:**\n\n```\npublic boolean closeStrings(String word1, String word2) {\n\tif (word1.length() != word2.length()) {\n\t\treturn false;\n\t}\n\tMap<Character, Integer> word1Map = new HashMap<>();\n\tMap<Character, Integer> word2Map = new HashMap<>();\n\tfor (char c : word1.toCharArray()) {\n\t\tword1Map.put(c, word1Map.getOrDefault(c, 0) + 1);\n\t}\n\tfor (char c : word2.toCharArray()) {\n\t\tword2Map.put(c, word2Map.getOrDefault(c, 0) + 1);\n\t}\n\tif (!word1Map.keySet().equals(word2Map.keySet())) {\n\t\treturn false;\n\t}\n\tList<Integer> word1FrequencyList = new ArrayList<>(word1Map.values());\n\tList<Integer> word2FrequencyList = new ArrayList<>(word2Map.values());\n\tCollections.sort(word1FrequencyList);\n\tCollections.sort(word2FrequencyList);\n\treturn word1FrequencyList.equals(word2FrequencyList);\n}\n```\n**Please do upvote if this is helpful and I will keep posting as best as I can!** | 57 | 2 | ['Java', 'Python3'] | 7 |
determine-if-two-strings-are-close | ✔️✔️JAVA || EASY APPROACH || DETAILED EXPLANATION || closeSTRING || | java-easy-approach-detailed-explanation-ax5uy | Two conditions required for satisfying a close string:\n1. All UNIQUE characters present in String 1 should be available in String 2 & vice versa.(NOT CONSIDERI | _dc | NORMAL | 2022-12-02T03:38:02.160887+00:00 | 2022-12-02T03:48:05.236865+00:00 | 3,767 | false | *Two conditions required for satisfying a close string:*\n*1. All UNIQUE characters present in String 1 should be available in String 2 & vice versa.(NOT CONSIDERING THEIR FREQUENCY).\n2. If condition 1 is satisfied then a Sorted Frequency Arr of One String should be same as the Sorted Frequency Arr of Other. \nIf both Conditions are true then its a closeString.*\n\n```\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n int freq1[]=new int [26];\n int freq2[]=new int [26];\n for(int i=0;i<word1.length();i++){\n freq1[word1.charAt(i)-\'a\']++;\n }\n for(int i=0;i<word2.length();i++){\n freq2[word2.charAt(i)-\'a\']++;\n }\n for(int i=0;i<26;i++){\n if((freq1[i]==0&&freq2[i]!=0)||(freq1[i]!=0&&freq2[i]==0))return false;\n }\n Arrays.sort(freq1);Arrays.sort(freq2);\n for(int i=0;i<26;i++){\n if(freq1[i]!=freq2[i])return false;\n }\n return true;\n }\n}\n``` | 29 | 1 | ['Java'] | 6 |
determine-if-two-strings-are-close | C++ Compare Frequencies | c-compare-frequencies-by-votrubac-q8dj | We can freely re-arrange charracters and their frequencies.\n\nSo, we need to check that;\n1. Both string have the same set of charracters.\n2. Both string have | votrubac | NORMAL | 2020-11-15T04:06:46.801756+00:00 | 2020-11-18T21:43:02.421205+00:00 | 3,320 | false | We can freely re-arrange charracters and their frequencies.\n\nSo, we need to check that;\n1. Both string have the same set of charracters.\n2. Both string have the same frequency of charracters.\n\n> E.g string "abbccddd" has [1, 2, 2, 3] char frequency, and so does "bddccaaa".\n\n```cpp\nbool closeStrings(string w1, string w2) {\n if (w1.size() != w2.size())\n return false;\n vector<int> cnt1(26), cnt2(26);\n for (auto i = 0; i < w1.size(); ++i) {\n ++cnt1[w1[i] - \'a\'];\n ++cnt2[w2[i] - \'a\'];\n }\n if (!equal(begin(cnt1), end(cnt1), begin(cnt2), end(cnt2), [](int a, int b) { return (bool)a == bool(b); }))\n return false;\n sort(begin(cnt1), end(cnt1));\n sort(begin(cnt2), end(cnt2));\n return cnt1 == cnt2;\n}\n``` | 29 | 4 | [] | 9 |
determine-if-two-strings-are-close | C++ O(NlogN) | Sort + Hash table | Easy to understand | c-onlogn-sort-hash-table-easy-to-underst-yw8v | Algorithm:\n 1.Find the frequency of every number\n 2.Sort them and compare their freq, if the same return true\n 3.Take care of the species of string | GoogleNick | NORMAL | 2020-11-15T04:00:38.757454+00:00 | 2020-11-15T04:05:17.175538+00:00 | 4,992 | false | Algorithm:\n 1.Find the frequency of every number\n 2.Sort them and compare their freq, if the same return true\n 3.Take care of the species of string (using unordered_set to check out), because we are only allow swap not create a new letter.\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n if(word1.size()!=word2.size())\n return false;\n int n = word1.size();\n vector<int>freq1(26,0);\n vector<int>freq2(26,0);\n for(int i= 0 ; i < n ; ++i){\n freq1[word1[i]-\'a\']++;\n freq2[word2[i]-\'a\']++;\n }\n sort(freq1.rbegin(),freq1.rend());\n sort(freq2.rbegin(),freq2.rend());\n if(set(word1.begin(),word1.end())!=set(word2.begin(),word2.end()))\n return false;\n for(int i= 0;i<26;++i){\n if(freq1[i]!=freq2[i])\n return false;\n }\n return true;\n }\n};\n``` | 22 | 1 | [] | 4 |
determine-if-two-strings-are-close | C++/Python Freq count & finds letters->1 liner||26 ms Beats 99.95% | cpython-freq-count-finds-letters-1-liner-6bb4 | Intuition\n Describe your first thoughts on how to solve this problem. \nStrings word1 and word2 are close $\iff$ the following 2 conditions are satisfied:\n1. | anwendeng | NORMAL | 2024-01-14T00:37:35.010044+00:00 | 2024-01-14T09:27:46.821888+00:00 | 4,245 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStrings word1 and word2 are close $\\iff$ the following 2 conditions are satisfied:\n1. Both strings consist of the same letter set.\n2. The frequencies of alphabets of 2 strings are mutual permutations.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[Please turn on English subtitles if necessary]\n[https://youtu.be/S7y-vIKvRKw?si=nMBtlJZ3d7hDF9Od](https://youtu.be/S7y-vIKvRKw?si=nMBtlJZ3d7hDF9Od)\n\nFor the checking the letter set, use the arrays `array<bool, 26> S1, S2` store the status for word1 & word2.\n\nFor checking whether they are permutations, use sort then compare.\n\nPython 1-liner is also provided.\n2nd C++ uses is_permutation in algorithm (TC: worst case $O(26^2)$) instead of sort& compare which runs in 34ms Beats 99.67%\n\n|Method| elapsed time| Time record | Space |\n|---|---|---|---|\n|C++ arrays & sort|26ms|99.95%|17.33MB|\n|C++ arrays & is_permutation|34ms|99.67%|17.51MB|\n|Python lists|234ms|27.42%|18.52MB|\n|Python 1-line set & Counter|116ms|93.83%|18.16MB|\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n+26\\times \\log_2(26))=O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(26)=O(1)$\n# Code\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n array<int, 26>& alpha(const string& word, array<bool, 26>& S){\n array<int, 26> A;\n A.fill(0);\n for(char c: word){\n int i=c-\'a\';\n S[i]=1;\n A[i]++;\n }\n return A;\n }\n\n bool closeStrings(string& word1, string& word2) {\n array<bool, 26> S1, S2;\n S1.fill(0), S2.fill(0);\n array<int, 26> A1=alpha(word1, S1);\n array<int, 26> A2=alpha(word2, S2);\n if (S1!=S2) return 0;\n sort(A1.begin(), A1.end());\n sort(A2.begin(), A2.end());\n return A1==A2;\n }\n};\n\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# Python solution\n```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n def alpha(word):\n freq=[0]*26\n S=[False]*26\n for c in word:\n i=ord(c)-ord(\'a\')\n S[i]=True\n freq[i]+=1\n return (S, freq)\n \n S1, A1=alpha(word1)\n S2, A2=alpha(word2)\n if S1!= S2: return False\n return sorted(A1)==sorted(A2)\n```\n# 2nd Python code is 1-liner|116ms Beats 93.83%\n```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n return set(word1)==set(word2) and sorted(Counter(word1).values())==sorted(Counter(word2).values())\n \n```\n# C++ using is_permutation|34ms Beats 99.67%\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n array<int, 26>& alpha(const string& word, array<bool, 26>& S){\n array<int, 26> A;\n A.fill(0);\n for(char c: word){\n int i=c-\'a\';\n S[i]=1;\n A[i]++;\n }\n return A;\n }\n\n bool closeStrings(string& word1, string& word2) {\n array<bool, 26> S1, S2;\n S1.fill(0), S2.fill(0);\n array<int, 26> A1=alpha(word1, S1);\n array<int, 26> A2=alpha(word2, S2);\n if (S1!=S2) return 0;\n return is_permutation(A1.begin(), A1.end(), A2.begin(), A2.end());\n }\n};\n\n``` | 21 | 1 | ['Array', 'String', 'Sorting', 'C++', 'Python3'] | 8 |
determine-if-two-strings-are-close | Easy solution with complete explaination | Most optimized (mazza aaega) | easy-solution-with-complete-explaination-l3u3 | Intuition\n Describe your first thoughts on how to solve this problem. \nAs the words can be swapped and interchanged, if we just think that certain char has sa | ankitraj15 | NORMAL | 2024-01-14T00:32:03.937637+00:00 | 2024-01-14T00:32:03.937661+00:00 | 2,605 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs the words can be swapped and interchanged, if we just think that certain char has same count in word1 with certain char of word2(can be different) to apna kaam bn gyaaa\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBahut hi khoobsurat approach, as letter should be same -> can be checked by set (apna dimag lagao kaise)\ncount of any char should be same of any char -> if we sort in vector then we can keep track of both the count.. (copy pe dry run kro.. chamkega)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n)\n\n# Code\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n int n=word1.size();\n int m=word2.size();\n set<char>s1,s2;\n vector<int>v1(26,0);\n vector<int>v2(26,0);\n if(n!=m) return false;\n\n for(int i=0;i<n;i++){\n s1.insert(word1[i]);\n s2.insert(word2[i]);\n v1[word1[i]-\'a\']++;\n v2[word2[i]-\'a\']++;\n }\n sort(v1.begin(),v1.end());\n sort(v2.begin(),v2.end());\n if(s1==s2 && v1==v2) return true;\n return false;\n \n }\n};\n``` | 19 | 1 | ['C++'] | 10 |
determine-if-two-strings-are-close | C++ Super-Simple & Easy Solution | c-super-simple-easy-solution-by-yehudisk-le4p | \nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n set<int> w1_letters, w2_letters, w1_freq, w2_freq;\n unordered_ | yehudisk | NORMAL | 2021-01-22T09:58:37.440424+00:00 | 2021-01-22T09:58:37.440469+00:00 | 1,906 | false | ```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n set<int> w1_letters, w2_letters, w1_freq, w2_freq;\n unordered_map<char, int> w1_m, w2_m;\n \n for (auto a : word1) {\n w1_letters.insert(a);\n w1_m[a]++;\n }\n \n for (auto a : word2) {\n w2_letters.insert(a);\n w2_m[a]++;\n }\n \n for (auto [k, v] : w1_m) w1_freq.insert(v);\n \n for (auto [k, v] : w2_m) w2_freq.insert(v);\n\n return w1_letters == w2_letters && w1_freq == w2_freq;\n }\n};\n```\n**Like it? please upvote...** | 19 | 3 | ['C'] | 5 |
determine-if-two-strings-are-close | Javascript | simple intuitive solution | javascript-simple-intuitive-solution-by-b2jk8 | Intuition\nGiven the rules, the two words will be "close" if they:\n- Have the same set of letters.\n- Have the same multiset (or bag) of letter counts.\n\n# Co | colkadome | NORMAL | 2022-12-02T09:48:44.759719+00:00 | 2022-12-02T09:48:44.759746+00:00 | 1,359 | false | # Intuition\nGiven the rules, the two words will be "close" if they:\n- Have the same set of letters.\n- Have the same multiset (or bag) of letter counts.\n\n# Complexity\n- Time complexity: O(nLogn)\n- Space complexity: O(n)\n\n# Code\n```\n\nfunction getSortedItems(word) {\n\n const group = {};\n\n for (let c of word) {\n group[c] = (group[c] || 0) + 1;\n }\n\n return {\n keys: Object.keys(group).sort(),\n counts: Object.values(group).sort((a, b) => a - b),\n };\n\n}\n\nvar closeStrings = function(word1, word2) {\n\n if (word1.length !== word2.length) {\n return false;\n }\n \n const group1 = getSortedItems(word1);\n const group2 = getSortedItems(word2);\n\n for (let i = 0; i < group1.keys.length; i++) {\n if (group1.keys[i] !== group2.keys[i] || group1.counts[i] !== group2.counts[i]) {\n return false;\n }\n }\n\n return true;\n\n};\n``` | 18 | 0 | ['JavaScript'] | 2 |
determine-if-two-strings-are-close | Golang Array | golang-array-by-hong_zhao-9cyl | go\nfunc closeStrings(word1 string, word2 string) bool {\n\tcounter := func(word string) (keys, vals [26]int) {\n\t\tfor i := range word {\n\t\t\tkeys[word[i]-\ | hong_zhao | NORMAL | 2022-12-02T01:54:59.037502+00:00 | 2022-12-02T01:54:59.037539+00:00 | 541 | false | ```go\nfunc closeStrings(word1 string, word2 string) bool {\n\tcounter := func(word string) (keys, vals [26]int) {\n\t\tfor i := range word {\n\t\t\tkeys[word[i]-\'a\'] = 1\n\t\t\tvals[word[i]-\'a\'] += 1\n\t\t}\n\t\tsort.Ints(vals[:])\n\t\treturn keys, vals\n\t}\n\tkeys1, vals1 := counter(word1)\n\tkeys2, vals2 := counter(word2)\n\treturn keys1 == keys2 && vals1 == vals2\n}\n``` | 14 | 0 | ['Go'] | 2 |
determine-if-two-strings-are-close | Determine if Two Strings Are Close | Python | Counter | determine-if-two-strings-are-close-pytho-davq | We come to two conclusions after analisys (hints are very helpful in this case):\n1. We cannot introduce new characters\n2. List of counts of characters will st | hollywood | NORMAL | 2021-01-22T10:12:40.971461+00:00 | 2021-01-22T10:18:00.952777+00:00 | 1,104 | false | We come to two conclusions after analisys (hints are very helpful in this case):\n1. We cannot introduce new characters\n2. List of counts of characters will stay consistent\n```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n # Saves some time\n if len(word1) != len(word2):\n return False\n \n from collections import Counter\n counts1 = Counter(word1)\n counts2 = Counter(word2)\n \n # No new chars can appear with operations\n if counts1.keys() != counts2.keys():\n return False\n \n # Counts can be swapped, but they will stay consistent\n if sorted(counts1.values()) != sorted(counts2.values()):\n return False\n \n return True\n\n``` | 14 | 0 | ['Python'] | 4 |
determine-if-two-strings-are-close | Python, Time: O(n)[100%], Space: O(n)[100%], clean, oneline | python-time-on100-space-on100-clean-onel-ofr8 | \n\n## One line solution\npython\n# Platform: leetcode.com\n# No. 1657. Determine if Two Strings Are Close\n# Link: https://leetcode.com/problems/determine-if-t | chumicat | NORMAL | 2020-11-15T05:16:10.433488+00:00 | 2020-11-15T06:18:25.963078+00:00 | 2,483 | false | \n\n## One line solution\n```python\n# Platform: leetcode.com\n# No. 1657. Determine if Two Strings Are Close\n# Link: https://leetcode.com/problems/determine-if-two-strings-are-close/\n# Difficulty: Medium\n# Dev: Chumicat\n# Date: 2020/11/15\n# Submission: https://leetcode.com/submissions/detail/420404393/\n# (Time, Space) Complexity : O(n), O(n)\n# 1. Check length for shortcut\n# 2. Check set for consist of character\n# 3. Check count count for consist of count\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n return len(word1) == len(word2) \\\n and set(word1) == set(word2) \\\n and Counter(Counter(word1).values()) == Counter(Counter(word2).values())\n```\n## You can reuse counter to accelerate\n```python\n# Platform: leetcode.com\n# No. 1657. Determine if Two Strings Are Close\n# Link: https://leetcode.com/problems/determine-if-two-strings-are-close/\n# Difficulty: Medium\n# Dev: Chumicat\n# Date: 2020/11/15\n# Submission: https://leetcode.com/submissions/detail/420421060/\n# (Time, Space) Complexity : O(n), O(n)\n# 1. Check length for shortcut\n# 2. Check set for consist of character\n# 3. Check count count for consist of count\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n if len(word1) != len(word2): return False \n \n c1, c2 = Counter(word1), Counter(word2) # Reuse of keys\n return c1.keys() == c2.keys() \\\n and Counter(c1.values()) == Counter(c2.values())\n```\n\n## Even further\nAnother things that I concerned is that str.count is muck more faster than Counter. I didn\'t confirm which will be faster:\n1. str.count check 26 times (or check set of string since we use it before)\n2. Counter check 1 time | 14 | 2 | ['Python3'] | 3 |
determine-if-two-strings-are-close | Simple java solution O(n) | simple-java-solution-on-by-raghu6306766-q6a0 | class Solution {\n \n\t \n\t /\n\t Strings are close only if \n\t 1) both words have same set of characters \n\t 2) the frequency of any character i | raghu6306766 | NORMAL | 2021-11-21T14:05:28.013223+00:00 | 2021-11-21T14:06:32.453069+00:00 | 1,140 | false | class Solution {\n \n\t \n\t /*\n\t Strings are close only if \n\t 1) both words have same set of characters \n\t 2) the frequency of any character in first word must be the frequency of any other character in the second word\n\t */\n\t public boolean closeStrings(String word1, String word2) {\n\t\t\tif(word1.length() != word2.length()) \n\t\t\t\treturn false;\n\t\t\t\n\t\t\t//create frequency map for corresponding words\n\t\t\tint[] freqMap1 = new int[26]; \n\t\t\tint[] freqMap2 = new int[26];\n\t\t\t\n\t\t\t//fill the maps with values\n\t\t\tword1.chars().forEach(i->freqMap1[i - 97]++);\n\t\t\tword2.chars().forEach(i->freqMap2[i - 97]++);\n\t\t\t\n\t\t\t//check if there exists a character that exisit in one word and does not exist in the other word\n\t\t\tfor(int i = 0 ; i < 26 ; i++)\n\t\t\t\tif(freqMap1[i] != 0 || freqMap2[i] != 0)\n\t\t\t\t\tif(freqMap1[i] == 0 || freqMap2[i] == 0)\n\t\t\t\t\t\treturn false;\n\t\t\t\n\t\t\t//sort both maps to compare values\n\t\t\tArrays.sort(freqMap1);\n\t\t\tArrays.sort(freqMap2);\n\t\t\n\t\t\t//check if any value is different\n\t\t\tfor(int i = 0 ; i < 26 ; i++)\n\t\t\t\tif(freqMap1[i] != freqMap2[i]) \n\t\t\t\t\treturn false;\n\n\t\t\treturn true;\n\t\t}\n} | 13 | 0 | ['Java'] | 1 |
determine-if-two-strings-are-close | Python: nlogn solution | python-nlogn-solution-by-peterl328-3rrj | Time complexity: O(nlogn):\n\n\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n c1 = collections.Counter(word1)\n c | peterl328 | NORMAL | 2020-11-15T04:02:25.545585+00:00 | 2022-02-28T03:47:39.922627+00:00 | 1,406 | false | Time complexity: `O(nlogn)`:\n\n```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n c1 = collections.Counter(word1)\n c2 = collections.Counter(word2)\n set1 = set(word1)\n set2 = set(word2)\n \n s1 = sorted(c1.values())\n s2 = sorted(c2.values())\n return s1 == s2 and set1 == set2:\n``` | 12 | 2 | [] | 2 |
determine-if-two-strings-are-close | Python3 using counter | python3-using-counter-by-discregionals-9l78 | \nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n \n # if they don\'t have the same length then\n # we can i | discregionals | NORMAL | 2022-12-02T00:34:29.736716+00:00 | 2022-12-02T01:08:48.382619+00:00 | 1,158 | false | ```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n \n # if they don\'t have the same length then\n # we can immediately return False\n if len(word1) != len(word2):\n return False\n \n else:\n c1 = Counter(word1)\n c2 = Counter(word2)\n \n # for 2 strings to be close they have to:\n \n # 1. \n # have the same number of repetitions (values),\n # they don\'t have to be the same character (key) necessarily\n \n # 2. \n # keys need to match because - task says: we can only \n # transform every occurrence of one existing character\n \n if (c1.keys() == (c2.keys())\n and sorted(c1.values()) == sorted(c2.values())):\n return True\n\n return False\n``` | 11 | 2 | ['Python3'] | 1 |
determine-if-two-strings-are-close | C++ || sort frequency count w/ some variants || fast (27ms, 100%?) | c-sort-frequency-count-w-some-variants-f-ndwr | Approach 1: frequency count letters and sort frequencies (32ms)\n\nSee inline comments below.\n\ncpp\n static bool closeStrings(const string& word1, const st | heder | NORMAL | 2022-12-02T00:32:48.650833+00:00 | 2022-12-02T14:29:26.044501+00:00 | 1,600 | false | # Approach 1: frequency count letters and sort frequencies (32ms)\n\nSee inline comments below.\n\n```cpp\n static bool closeStrings(const string& word1, const string& word2) {\n // Short circuit different word lengths.\n if (size(word1) != size(word2)) return false;\n\n return signature(word1) == signature(word2);\n }\n \n // Two observations:\n // 1. With operation 1 we can sort the word.\n // 2. With operation 2 we can assign freely assign the the\n // letter frequencies of all the letters in the word.\n // With that we frequency count the letters and then assign\n // the frequencies in descending order amount to the present\n // letters.\n static array<int, 26> signature(const string& word) {\n array<int, 26> freq = {};\n for (char ch : word) ++freq[ch - \'a\'];\n array<int, 26> ans = freq;\n sort(begin(freq), end(freq), greater<>());\n for (int i = 0, j = 0; i < size(ans); ++i)\n if (ans[i]) ans[i] = freq[j++];\n return ans;\n }\n```\n\n## Variant 1: "seen" bitset\n\nA variant of the signature function could be to use a bit set for the letters we see and just stick this into the signature after sorting the frequencies.\n\n```cpp\n static array<int, 27> signature(const string& word) {\n array<int, 27> ans = {};\n int seen = 0;\n for (char ch : word) {\n ch -= \'a\';\n ++ans[ch];\n seen |= 1 << ch;\n }\n sort(begin(ans), end(ans));\n ans[26] = seen;\n return ans;\n }\n```\n\n## Variant 2: rearrage signature for earlier mismatch (27ms)\n\nHere we move the bit mask with which letters are present to the beginning and sort the frequencies descending so we have an ealier mismatch if the signatures are not the same instead of comparing a sequence of zeros at first.\n\n```cpp\n static array<int, 27> signature(const string& word) {\n array<int, 27> ans = {};\n int seen = 0;\n for (char ch : word) {\n ch -= \'a\' - 1;\n ++ans[ch];\n ans[0] |= 1 << ch;\n }\n\t\t// sort ans[1] to ans[26], i.e. keep ans[0] in place.\n sort(next(begin(ans)), end(ans), greater<>());\n return ans;\n }\n```\n\n## Variant 3: do less work when scanning the word (27ms)\n\nThis is inspired by a solution from @martin0327\n\n```cpp\n static array<int, 27> signature(const string& word) {\n array<int, 27> ans = {};\n for (char ch : word) ++ans[ch - \'a\' + 1];\n for (int i = 1; i < size(ans); ++i)\n if (ans[i]) ans[0] |= 1 << i;\n\t\t// sort ans[1] to ans[26], i.e. keep ans[0] in place.\n sort(next(begin(ans)), end(ans), greater<>());\n return ans;\n }\n```\n\n## Variant 4: exit early if the set of letters is not the same\n\nWith a bit more duplicate code, of which some could be factored out, we can exit early before sorting the letter frequencies.\n\n```cpp\n static bool closeStrings(const string& word1, const string& word2) {\n // Short circuit different word lengths.\n if (size(word1) != size(word2)) return false;\n \n array<int, 26> sig1 = {};\n int seen1 = 0;\n for (char ch : word1) {\n ch -= \'a\';\n ++sig1[ch];\n seen1 |= 1 << ch;\n }\n\n array<int, 26> sig2 = {};\n int seen2 = 0;\n for (char ch : word2) {\n ch -= \'a\';\n ++sig2[ch];\n seen2 |= 1 << ch;\n }\n \n // Exit early if we are not seeing the same set of letters.\n if (seen1 != seen2) return false;\n \n sort(begin(sig1), end(sig1), greater<>());\n sort(begin(sig2), end(sig2), greater<>());\n\n return sig1 == sig2;\n }\n```\n\nLooking through some other posts, there are many more ways to solve this. Kinda nice, if there are many different ways to solve a problem.\n\n**Complexity Analysis**\nLet $$n$$ the length of the words then\n * Time complexity is $$O(n)$$, because we need to scan over both words. Note that we are only sorting a fixed length arrays regardless of the length of the words, and hence this remains constant time. The\n * Space complexity is $$O(1)$$.\n\n_As always: Feedback, questions, and comments are welcome. Leaving an up-vote sparks joy! :)_\n\n**p.s. Join us on the [LeetCode The Hard Way Discord Server](https://discord.gg/hFUyVyWy2E)!** | 11 | 0 | ['C'] | 3 |
determine-if-two-strings-are-close | easy solution in c++ | easy-solution-in-c-by-dhawalsingh564-stzv | Solution is based on counting like;\n1-) If both the strings have same character same number of times and the another string is jumbled then definitely they wil | dhawalsingh564 | NORMAL | 2021-01-22T12:07:03.059187+00:00 | 2021-01-22T17:16:29.203940+00:00 | 846 | false | Solution is based on counting like;\n1-) If both the strings have same character same number of times and the another string is jumbled then definitely they will be same we dont even think about jumbling and all and try to make one string into another string.\n\n2) word1: count frequencies a=1,b=3,c=5,d=8; // sort: 1 3 5 8\nword2: count freq a=5,b=1,c=8,d=3; // sort: 1 3 5 8\n\njust match each no is present or not by sorting.(alongwith check some extra conditions)\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n \n unordered_map<char,int> m;\n unordered_map<char,int> v;\n int i,j;\n int n=word1.length();\n int c=word2.length();\n \n if(n!=c)\n return false;\n \n for(i=0;i<n;i++)\n {\n m[word1[i]]++;\n v[word2[i]]++;\n } \n if(m.size()!=v.size())\n return false;\n \n vector<int> w1;\n vector<int> w2;\n for(auto it: m)\n {\n if(v[it.first]==0)\n return false;\n \n w1.push_back(it.second);\n w2.push_back(v[it.first]);\n }\n sort(w1.begin(),w1.end());\n sort(w2.begin(),w2.end());\n \n for(i=0;i<w1.size();i++)\n {\n if(w1[i]!=w2[i])\n return false;\n }\n return true;\n }\n};\n``` | 11 | 1 | [] | 6 |
determine-if-two-strings-are-close | Easy understable approach!!!^_^😉 | easy-understable-approach_-by-lijoice-8icp | Intuition\n- The problem asks whether two strings are "close." Intuitively, two strings can be considered "close" if:\n\n1. They contain the same set of unique | lijoice | NORMAL | 2024-09-04T14:03:05.017254+00:00 | 2024-09-04T14:03:05.017281+00:00 | 731 | false | # Intuition\n- The problem asks whether two strings are "close." Intuitively, two strings can be considered "close" if:\n\n1. They contain the same set of unique characters.\n2. The frequency of characters in one string can be rearranged to match the frequency of characters in the other string.\n\nTo determine this, we can use frequency arrays to keep track of character occurrences and then compare the sorted frequency distributions.\n\n# Approach\n**Frequency Arrays:**\n\n1. Create two frequency arrays (freq1 and freq2) for the 26 lowercase English letters.\n2. Traverse word1 and word2 to populate these arrays with the frequency of each character.\n**Character Set Check:**\n\n- Ensure both strings have the same set of unique characters. If word1 has a character that word2 lacks (or vice versa), the strings cannot be close.\n**Frequency Comparison:**\n\n- Sort both frequency arrays.\n- Compare the sorted arrays. If they match, it means that the character frequencies can be rearranged in one string to match the other.\n**Return Result:**\n\n- If all conditions are met, return true, indicating the strings are "close"; otherwise, return false.\n\n# Complexity\n# - Time complexity:\nThe dominant step is the frequency counting, which takes O(n + m), where n is the length of word1 and m is the length of word2.\nSorting the frequency arrays takes O(26 log 26), which simplifies to O(1) because the size of the arrays is constant.\nOverall, the time complexity is O(n + m).\n\n# - Space complexity:\nThe space complexity is O(1), as the frequency arrays are of fixed size (26 elements each), and no additional space is required that scales with the input size.\n\n# Code\n```java []\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n int[] freq1=new int[26];\n int[] freq2=new int[26];\n for (char ch : word1.toCharArray()){\n freq1[ch-\'a\']++;\n }\n for(char ch: word2.toCharArray()){\n freq2[ch-\'a\']++;\n }\n for(int i=0;i<26;i++){\n if((freq1[i]==0 && freq2[i]!=0) || (freq2[i]==0 && freq1[i]!=0)){\n return false;\n }\n }\n Arrays.sort((freq1));\n Arrays.sort(freq2);\n\n for (int i=0;i<26;i++){\n if (freq1[i] != freq2[i]){\n return false;\n }\n }\n return true;\n }\n}\n``` | 10 | 0 | ['Java'] | 2 |
determine-if-two-strings-are-close | C++ | Compare Frequency Approach | Linear Time Complexity | c-compare-frequency-approach-linear-time-rttq | Basic Idea : \n\nIf the two strings are close, then \n They must have the same set of characters.\n The frequency of each character in each string must be the s | Raveena_Bhasin | NORMAL | 2022-12-02T04:50:43.966770+00:00 | 2022-12-02T04:50:43.966801+00:00 | 569 | false | **Basic Idea :** \n\nIf the two strings are close, then \n* They must have the same set of characters.\n* The frequency of each character in each string must be the same.\n\n\n**C++ Solution**\n```\n\tbool closeStrings(string word1, string word2) {\n\t\tif(word1.size() != word2.size()) return false; // check if the two words are of equal length\n\t\tvector<int> v1(26,0), v2(26,0); // initialise two vectors of size 26 with all entries as 0\n\t\tfor(char ch: word1) v1[ch-\'a\']++; // count the number of each character in word1 and increment the corresponding index in v1\n\t\tfor(char ch: word2) v2[ch-\'a\']++; // count the number of each character in word2 and increment the corresponding index in v2\n\t\tfor(int i=0; i<26; i++){ // check if there is a character in word1 and not in word2 or vice versa\n\t\t\tif((v1[i] == 0 && v2[i] != 0) || (v1[i] != 0 && v2[i] == 0)) return false;\n\t\t}\n\t\tsort(v1.begin(), v1.end()); // sort the two vectors\n\t\tsort(v2.begin(), v2.end());\n\t\treturn v1 == v2; // check if the two vectors are equal\n\t}\n``` | 10 | 0 | [] | 2 |
determine-if-two-strings-are-close | ✅Four Java Simple Solutions || ✅Runtime 7ms || ✅ 99.8% | four-java-simple-solutions-runtime-7ms-9-qida | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ahmedna126 | NORMAL | 2024-01-14T14:31:02.295911+00:00 | 2024-01-17T21:48:32.261369+00:00 | 374 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n\n# Code1\n| Runtime : **7ms** And Beats : **99.8%** \n```\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n if(word1.length() != word2.length()) return false;\n if (word1.equals(word2)) return true; \n byte[] ch1 = word1.getBytes() , ch2 = word2.getBytes();\n int [] arr1 = new int[26] , arr2 = new int[26];\n\n for (byte c : ch1){\n arr1[c - \'a\']++;\n }\n\n for (byte c : ch2)\n {\n if (arr1[c - \'a\'] == 0) return false;\n arr2[c - \'a\']++;\n }\n\n Arrays.sort(arr1);\n Arrays.sort(arr2);\n\n // return Arrays.equals(arr1 , arr2);\n int i = 25;\n while (arr1[i] != 0 && i > 0 )\n {\n if (arr1[i] != arr2[i]) return false;\n i--;\n }\n\n return true;\n }\n}\n```\n\n# Code2\n| Runtime : **8ms** And Beats : **99.7%** \n```java\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n if (word1.length() != word2.length()) return false;\n if (word1.equals(word2)) return true;\n\n int[] arr1 = new int[26];\n int[] arr2 = new int[26];\n\n for (char c : word1.toCharArray()) {\n arr1[c - \'a\']++;\n }\n\n for (char c : word2.toCharArray()) {\n if (arr1[c - \'a\'] == 0) return false;\n arr2[c - \'a\']++;\n }\n\n for (int n : arr1) {\n if (n != 0) {\n int index = -1;\n for (int i = 0; i < 26; i++) {\n if (arr2[i] == n) {\n index = i;\n break;\n }\n }\n if (index == -1) return false;\n arr2[index] = 0;\n }\n }\n\n return true;\n }\n}\n```\n\n# Code3 \n| Runtime : **32ms** And Beats : **54%** \n\n```Java\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n if(word1.length() != word2.length()) return false;\n HashSet<Character> hashSet = new HashSet<>();\n char[] ch1 = word1.toCharArray() , ch2 = word2.toCharArray();\n int [] arr1 = new int[26] , arr2 = new int[26];\n\n for (char c : ch1)\n {\n hashSet.add(c);\n arr1[c - \'a\']++;\n }\n for (char c : ch2)\n {\n if (!hashSet.contains(c)) return false;\n arr2[c - \'a\']++;\n }\n\n Arrays.sort(arr1);\n Arrays.sort(arr2);\n\n return Arrays.equals(arr1 , arr2);\n }\n}\n```\n\n<!-- # Code3\n| Runtime : **79ms** And Beats : **24%** \n\n```Java\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n if (word1.length() != word2.length()) return false;\n\n ConcurrentHashMap<Character, Integer> hashMap1 = new ConcurrentHashMap<>();\n ConcurrentHashMap<Character, Integer> hashMap2 = new ConcurrentHashMap<>();\n\n // Count character occurrences in word1\n word1.chars().forEach(ch -> hashMap1.merge((char) ch, 1, Integer::sum));\n\n // Count character occurrences in word2\n word2.chars().forEach(ch -> hashMap2.merge((char) ch, 1, Integer::sum));\n\n if (!hashMap1.keySet().equals(hashMap2.keySet())) return false;\n\n // Compare frequency arrays directly\n int[] arr1 = hashMap1.values().stream().mapToInt(Integer::intValue).toArray();\n int[] arr2 = hashMap2.values().stream().mapToInt(Integer::intValue).toArray();\n\n Arrays.sort(arr1);\n Arrays.sort(arr2);\n\n return Arrays.equals(arr1, arr2);\n }\n}\n``` -->\n\n# Code4\n| Runtime : **86ms** And Beats : **19.5%** \n\n```Java\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n if(word1.length() != word2.length()) return false;\n char[] ch1 = word1.toCharArray() , ch2 = word2.toCharArray();\n\n ConcurrentHashMap<Character , Integer> hashMap1 = new ConcurrentHashMap<>();\n ConcurrentHashMap<Character , Integer> hashMap2 = new ConcurrentHashMap<>();\n\n for (int i = 0; i < ch1.length ; i++)\n {\n //or hashMap1.merge(ch1[i], 1, Integer::sum);\n hashMap1.put(ch1[i] , hashMap1.getOrDefault(ch1[i] , 0) + 1) ;\n hashMap2.put(ch2[i] , hashMap2.getOrDefault(ch2[i] , 0) + 1) ;\n }\n\n if (hashMap1.size() != hashMap2.size()) return false;\n\n int [] arr1 = new int[hashMap1.size()] , arr2 = new int[hashMap1.size()];\n\n int i = 0;\n for (Map.Entry<Character , Integer> map : hashMap1.entrySet())\n {\n arr1[i] = map.getValue();\n if (!hashMap2.containsKey(map.getKey())) return false;\n arr2[i] = hashMap2.get(map.getKey());\n i++;\n }\n Arrays.sort(arr1);\n Arrays.sort(arr2);\n return Arrays.equals(arr1 , arr2);\n }\n}\n```\n\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository](https://github.com/ahmedna126/java_leetcode_challenges)\n\n\n | 9 | 0 | ['Array', 'Hash Table', 'Sorting', 'Java'] | 0 |
determine-if-two-strings-are-close | ✅✅Java easy solution||Beginner friendly||Smoooooooooth🧈 | java-easy-solutionbeginner-friendlysmooo-mkfg | Close Strings\n\n### Problem Statement\n\nTwo strings are considered close if you can attain one from the other using the following operations:\n\n1. Operation | jeril-johnson | NORMAL | 2024-01-14T05:02:28.145110+00:00 | 2024-01-14T05:02:28.145139+00:00 | 1,540 | false | ## Close Strings\n\n### Problem Statement\n\nTwo strings are considered **close** if you can attain one from the other using the following operations:\n\n1. **Operation 1:** Swap any two existing characters.\n2. **Operation 2:** Transform every occurrence of one existing character into another existing character, and do the same with the other character.\n\nGiven two strings, `word1` and `word2`, return `true` if `word1` and `word2` are close, and `false` otherwise.\n\n### Example\n\n```java\nInput: word1 = "abc", word2 = "bca"\nOutput: true\nExplanation: You can attain word2 from word1 in 2 operations.\nApply Operation 1: "abc" -> "acb"\nApply Operation 1: "acb" -> "bca"\n```\n\n### Approach\n\n1. Check if the lengths of `word1` and `word2` are equal. If not, return `false` because it is not possible to transform one string into the other with different lengths.\n2. Count the frequency of each character in both `word1` and `word2`.\n3. For each character in the alphabet, check if it appears in either `word1` or `word2` but not in both. If yes, return `false` because the set of characters must be the same for both strings.\n4. Sort the frequency arrays of both `word1` and `word2`. This is done to compare if the frequency of each character is the same in both strings.\n5. Iterate through the sorted frequency arrays and check if the frequencies are equal for each character. If not, return `false`.\n6. If the loop completes without returning `false`, return `true`.\n\n### Implementation\n\n```java\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n if (word1.length() != word2.length())\n return false;\n\n int[] f1 = new int[26];\n int[] f2 = new int[26];\n\n // Count frequency of each character in both words\n for (int i = 0; i < word1.length(); i++) {\n f1[word1.charAt(i) - \'a\']++;\n f2[word2.charAt(i) - \'a\']++;\n }\n\n // Check if the set of characters is the same for both words\n for (int i = 0; i < 26; i++) {\n if ((f1[i] == 0 && f2[i] != 0) || (f1[i] != 0 && f2[i] == 0))\n return false;\n }\n\n // Sort frequency arrays\n Arrays.sort(f1);\n Arrays.sort(f2);\n\n // Check if the frequency of each character is the same\n for (int i = 0; i < 26; i++) {\n if (f1[i] != f2[i])\n return false;\n }\n\n return true;\n }\n}\n```\n\n### Complexity Analysis\n\nThe time complexity is O(n), where n is the length of `word1` or `word2`.\nThe space complexity is O(1) because the size of the alphabet (26) is constant. | 9 | 0 | ['Java'] | 3 |
determine-if-two-strings-are-close | Python 3 || 1-9 lines, Counters and Sets, w/ explanation and example || T/S: 68% / 99% | python-3-1-9-lines-counters-and-sets-w-e-u9tc | The problem is equivalent to showing that (a) word1 and word2 have the same set of distinct characters, and (b) the collection of counts for distinct characters | Spaulding_ | NORMAL | 2022-12-02T17:58:55.013802+00:00 | 2024-06-11T00:37:55.715104+00:00 | 2,354 | false | The problem is equivalent to showing that (a) `word1` and `word2` have the same set of distinct characters, and (b) the collection of counts for distinct characters for `word1` and `word2` are identical. (The counts for the same letter do not have to be equal, however.) We use *Counters* to determine (a) and *sets* to determine (b).\n```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool: # Example: word1 = "cabbba" \n # word2 = "abbccc"\n\n c1 = Counter(word1) # c1 = {\'a\':2, \'b\':3, \'c\':1}\n c2 = Counter(word2) # c1 = {\'a\':2, \'b\':3, \'c\':1}\n\n count1 = sorted(c1.values()) # count1 = [1, 2, 3]\n count2 = sorted(c2.values()) # count2 = [1, 2, 3]\n\n set1 = set(word1) # set1 = {\'c\', \'b\', \'a\'}\n set2 = set(word2) # set2 = {\'a\', \'c\', \'b\'}\n\n if count1 == count2 and set1 == set2: # return True\n return True\n\n return False\n```\n[https://leetcode.com/problems/determine-if-two-strings-are-close/submissions/1279723340/](https://leetcode.com/problems/determine-if-two-strings-are-close/submissions/1279723340/)\n\nI could be wrong, but I think that time complexity is *O*(*N* log *N*) and space complexity is *O*(*N* log *N*), in which *N* ~ `len(word1)`.\n\nHere\'s a one-liner:\n```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n \n return sorted(Counter(word1).values()) == sorted(Counter(word2).values()) and set(word1) == set(word2)\n | 9 | 0 | ['Ordered Set', 'Python'] | 2 |
determine-if-two-strings-are-close | Vectorization and Partial Sort. 15 ms in C++ Beating 100%. | vectorization-and-partial-sort-15-ms-in-6ukkn | Intuition\nFrom the description of operations it is clear that we should compare strings in such a way that:\n1. Order of characters within the strings is insig | sergei99 | NORMAL | 2024-01-14T19:34:24.082060+00:00 | 2024-01-14T19:44:14.186102+00:00 | 529 | false | # Intuition\nFrom the description of operations it is clear that we should compare strings in such a way that:\n1. Order of characters within the strings is insignificant. So we can apply counting here.\n2. Frequences of characters can be shuffled in any manner with the only restriction: we can only exchange non-zero frequences. Zero frequencies stay where they are.\n\nThe alphabet consists of lowercase English letters, i.e. has a cardinality of $26$.\nThe strings can be up to $10^5$ characters long.\n\n# Approach\nFor each string we build a frequency profile: an array of 26 counters reflecting the number of occurrences of each character within the string. We should compare such frequency profiles for equality up to their element order and return the comparison result. First of all, that means that the sums of frequencies should match, as such, strings should be of equal length. Therefore we can discard strings of different lengths early.\n\nWe can\'t get away with a single array incrementing/decrementing counters here because we don\'t know in advance how do we match frequency profiles. E.g. which letter in the second string would correspond to `a`? No idea until we traverse both strings.\n\nHow do we build the profiles? Reading character by character in a loop, incrementing the relevant counters, and achieving some kind of a "Beating 98%" solution? I guess we can leave that approach to high schools. We have strings up to 100k characters long, and we should try to process them quickly, particularly minimizing conditional jumps and bundling memory access. As most of the mainstream architectures are 64 bit, we can read 8 characters at a time, bias them by `"aaaaaaaa"` in a single operation and only then split them to individual indexes into frequencies arrays. That would give us 8 times fewer branching and perfectly aligned memory access. The strings\' lengths of course don\'t have to be divisible by 8, so we process a possible remainder in a scalar "high school" way. As strings have equal lengths at this stage, we process both of them in a single vector and a single scalar loop. At the end of this stage we have two arrays containing per character frequencies.\n\nNow that we have frequency profiles, how to we match them, considering that their order is not important, only zeroes cannot be matched with non-zeroes? Most solutions go for sorting in this case. Is this really efficient? Let\'s take a look at it.\n\nA typical general-purpose library sort function has an asymptotic complexity of $O(n \\times log(n))$. Usually it has so little information about the keys that it has to go for one of $n \\times log_2(n)$ algorithms, resulting in our case in $26 \\times 5 \\times 2 = 260$ comparisons and swaps for two arrays. That\'s not to mention that e.g. Hoare sort has an $O(n^2)$ worst case complexity.\n\nCan we get away with a faster sorting approach, e.g. count sort? Not really because frequencies can occupy too wide ranges (up to $10^5$, remember). Walking through such a long array would defeat the purpose of using a linear complexity sorting algorithm. Radix sort perhaps? That wouldn\'t pay off on a 26-element array.\n\nOn the other hand, do we even need sorting here? We are perfectly happy with one array retaining its order, whatever chaotic it might be, and the order of the another array just brought to it. This sounds like some kind of a partial sort. We can walk through the frequency arrays `freqs1` and `freqs2` and swap the second array\'s elements so that `freqs1[i] == freqs2[i]` for each `i`. This would require a nested loop over the remainder of the second array. In order to prevent an $O(A^2)$ scenario (where $A$ is the alphabet size), we place as much elements as possible to their target positions during each traversal.\n\nConsider e.g. these profiles:\n| a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z |\n|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|\n| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |\n| 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 1 |\n\nAt index 0 of the outer loop we have mismatching frequencies. So we need to find frequency `1` in the second array. It resides at the end of the array, so we would have to traverse it till the end in the inner loop.\n\nHowever we take the "working value" of `2` and compare it to the elements of the first array. We see that the second element of the first array matches our working value, so we write `2` at the index 1 of the second array and pick up `3` as our working value. `3` would be written at the next inner loop iteration because it matches the first array\'s element again. And the final `1` would be written to the first element. In this example we would write every single element in the first pass, and all subsequent iterations of the outer loop won\'t start the inner loop at all. There would be just 2 traversals.\n| a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z |\n|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|\n| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |\n| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |\n\nWhat if we didn\'t have such a perfectly ordered data? E.g.:\n| a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z |\n|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|\n| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |\n| 2 | 4 | 5 | 6 | 3 | 8 | 9 | 10 | 7 | 12 | 13 | 14 | 11 | 16 | 17 | 18 | 15 | 20 | 21 | 22 | 19 | 24 | 25 | 26 | 23 | 1 |\n\nIn this case `2` would still be written at index 1, then the next working value `4` would be written at index 3, `6` would be written at index 5, etc. So we would position more than half of the elements correctly in the first pass.\n| a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z |\n|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|\n| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |\n| 1 | 2 | 5 | 4 | 3 | 6 | 9 | 8 | 7 | 10 | 13 | 12 | 11 | 14 | 17 | 16 | 15 | 18 | 21 | 20 | 19 | 22 | 25 | 24 | 23 | 26 |\n\nThe second iteration of the outer loop would compare `2` and `2` and proceed to the third iteration, which would exchange `3` and `5`, traversing just 2 additional elements for that. In total there would be $2$ complete passes ($1$ outer + $1$ inner) and $6$ short passes through $\\times 2$ elements, which is $26 \\times 2 + 6 \\times 2 = 64$ operations. It would be a rare occasion that this requires $130$ operations (which a sort function would normally do for one array), let alone $260$.\n\nWe also never move zero elements, they are only for comparison. Two zeroes at the same position are a match, and if one array contains a zero and another one does not, then we exit early with a `false` return value. This is another advantage over the general-purpose sort operation which would have to move zeroes as well as any other elements.\n\n# Complexity\n- Time complexity: $O(n + A^2)$.\n- Space complexity: $O(A)$.\n (where $A$ is the alphabet cardinality)\n\n# Micro-optimizations\n\nString parameters passed by reference (C++). Remember that STL strings are not shareable, so they are copied when passed by value.\n\nThe solution method declared static because we don\'t need any instance data here.\n\n`stdio` sync has been disabled, as usually.\n\n# Measurements\n\n| Language | Time | Beating | Memory | Beating |\n|-|-|-|-|-|\n| C++ | 15 ms | 100% | 17.36 Mb | 99.91% |\n\nThe former time record displayed by LC is 24 ms at the moment.\n\nA scalar counting solution with a slightly less efficient comparison has approached 23 ms, thus also beating the record. But we see how even a simple vectorization on general purpose registers (not even using an AVX) can improve performance.\n\nSubmission links:\nVectorized counting: https://leetcode.com/problems/determine-if-two-strings-are-close/submissions/1146196356/\nScalar counting: https://leetcode.com/problems/determine-if-two-strings-are-close/submissions/1145892554/\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n static bool closeStrings(const string &word1, const string &word2) {\n constexpr uint8_t ASIZE = 26, CMASK = 0x1Fu;\n constexpr uint64_t BIAS64 = 0x6161616161616161ull;\n const unsigned n = word1.length(), n64 = n >> 3;\n const char *const w1 = word1.c_str(), *const w2 = word2.c_str();\n const uint64_t *const w1q = reinterpret_cast<const uint64_t*>(w1),\n *const w2q = reinterpret_cast<const uint64_t*>(w2);\n if (n != word2.length()) return false;\n unsigned freqs1[ASIZE] = {}, freqs2[ASIZE] = {};\n for (unsigned i64 = 0; i64 < n64; i64++) {\n const uint64_t v1 = w1q[i64] - BIAS64;\n freqs1[v1 & CMASK]++;\n freqs1[(v1 >> 8) & CMASK]++;\n freqs1[(v1 >> 16) & CMASK]++;\n freqs1[(v1 >> 24) & CMASK]++;\n freqs1[(v1 >> 32) & CMASK]++;\n freqs1[(v1 >> 40) & CMASK]++;\n freqs1[(v1 >> 48) & CMASK]++;\n freqs1[v1 >> 56]++;\n const uint64_t v2 = w2q[i64] - BIAS64;\n freqs2[v2 & CMASK]++;\n freqs2[(v2 >> 8) & CMASK]++;\n freqs2[(v2 >> 16) & CMASK]++;\n freqs2[(v2 >> 24) & CMASK]++;\n freqs2[(v2 >> 32) & CMASK]++;\n freqs2[(v2 >> 40) & CMASK]++;\n freqs2[(v2 >> 48) & CMASK]++;\n freqs2[v2 >> 56]++;\n }\n for (unsigned i = n64 << 3; i < n; i++) {\n freqs1[w1[i]-\'a\']++;\n freqs2[w2[i]-\'a\']++;\n }\n for (uint8_t c = 0; c < ASIZE; c++) {\n const auto f1 = freqs1[c];\n auto &f2 = freqs2[c];\n if (f1 == f2) continue;\n if (f1 == 0 || f2 == 0) return false;\n auto fw = f2;\n uint8_t d;\n for (d = c + 1u; d < ASIZE; d++) {\n auto &f1d = freqs1[d], &f2d = freqs2[d];\n if (f1d != f2d) {\n if (f1 == f2d) break;\n if (f1d == fw) swap(f2d, fw);\n }\n }\n if (d >= ASIZE) return false;\n f2 = freqs2[d];\n freqs2[d] = fw;\n }\n return true;\n }\n};\n``` | 8 | 1 | ['String', 'Counting', 'C++'] | 1 |
determine-if-two-strings-are-close | 🚀🚀 Beats 100% | 30ms | Most Easiest Solution | Fully Explained 🔥🔥 | beats-100-30ms-most-easiest-solution-ful-zigq | Intuition:\n\n\uD83E\uDD14 The code checks if two strings are "close," meaning they have the same set of characters with the same frequency. The idea is to coun | The_Eternal_Soul | NORMAL | 2024-01-14T05:02:56.576104+00:00 | 2024-01-14T05:02:56.576125+00:00 | 1,563 | false | **Intuition:**\n\n\uD83E\uDD14 The code checks if two strings are "close," meaning they have the same set of characters with the same frequency. The idea is to count the frequency of each character in both strings and then compare whether the frequency distributions are equivalent.\n\n**Approach:**\n\n1. \uD83E\uDDEE Count the frequency of each character in both strings using two arrays (`freq1` and `freq2`).\n2. \uD83D\uDD04 Iterate through each character in the first array (`freq1`) and try to find a matching frequency in the second array (`freq2`).\n3. \u2705 If a matching frequency is found, mark it as visited by setting the corresponding element in `freq2` to -1.\n4. \u274C If a match is not found for any character, return false.\n5. \uD83D\uDD04 Repeat until all characters in `freq1` are processed.\n6. \u2714\uFE0F If the loop completes without returning false, the strings are considered "close," and the function returns true.\n\n**Time Complexity:**\n\n\u23F0 The time complexity is O(n), where n is the length of the input strings. This is because the code iterates through each character in both strings and performs constant-time operations for each character.\n\n**Space Complexity:**\n\n\uD83D\uDCBE The space complexity is O(1) because the size of the arrays (`freq1` and `freq2`) is fixed at 26, regardless of the input string lengths. The space required is constant and does not scale with the input size.\n\n# Code\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n\n int freq1[26] = {0};\n int freq2[26] = {0};\n\n for(auto x : word1)\n {\n freq1[x-\'a\']++;\n }\n\n for(auto x : word2)\n {\n freq2[x-\'a\']++;\n }\n\n for(int i = 0; i < 26; i++)\n {\n int curr = freq1[i];\n bool found = false;\n for(int j = 0; j < 26; j++)\n {\n if(freq2[j] == -1) continue;\n\n if((i == j) and ((freq1[i] != 0 and freq2[j] == 0) or (freq1[i] == 0 and freq2[j] != 0))) return false;\n \n if(curr != freq2[j]) \n continue;\n else if(curr == freq2[j])\n {\n found = true;\n freq2[j] = -1;\n break;\n }\n }\n if(found == false)\n return false;\n }\n\n return true;\n }\n};\n```\n\n------------------------------\uD83D\uDC96 UPVOTE PLEASE \uD83D\uDC96----------------------------- | 8 | 0 | ['Hash Table', 'String', 'C', 'Counting', 'Python', 'C++', 'Java', 'JavaScript'] | 1 |
determine-if-two-strings-are-close | (O(n)⏱️|💯%) JAVA☕ PYTHON🐍 JAVASCRIPT💛 TYPESCRIPT🔷 C++🦾 C##️⃣ Character Count🪄 | on-java-python-javascript-typescript-c-c-9xrg | Github - https://github.com/VishnuThangaraj \uD83D\uDE3A\n\n# Intuition\uD83E\uDDE0\n Describe your first thoughts on how to solve this problem. \nComparing the | VishnuThangaraj | NORMAL | 2024-01-14T02:35:07.937490+00:00 | 2024-01-14T11:48:41.502162+00:00 | 1,359 | false | Github - https://github.com/VishnuThangaraj \uD83D\uDE3A\n\n# Intuition\uD83E\uDDE0\n<!-- Describe your first thoughts on how to solve this problem. -->\nComparing the character count in both strings (word1 | word2) and Storing the frequency of characters in seperate array and comparing to determine the two strings are close or not.\n\n# Approach\u26A1\n<!-- Describe your approach to solving the problem. -->\n1. **COUNTING FREQUENCY**\n - Initialize arrays, `frequency1` and `frequency2` which stores the frequency of the characters in `word1` and `word2`.\n - `Frequency[index]` , where **index == i th** letter of the alphabet.\n2. **CHECK CHARACTER PRESENCE**\n - Iterate through the frequency arrays.\n - If a character present in one word and not in another, Return **False**\n - Both words should contain same set of characters, regardless of its count.\n3. **SORTING FREQUENCY ARRAY**\n - Sort the frequency arrays and compare the count of the frequency in both array.\n - If Both array has same number in count , Return **True** else **False**.\n\n# Complexity\u231B\n- Time complexity: `O(n)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(1)`, Since the size of the frequency arrays are constant.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\uD83D\uDCBB\n``` Java []\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n int[] frequency1 = new int[26];\n int[] frequency2 = new int[26];\n\n for(char letter : word1.toCharArray())\n frequency1[letter - \'a\']++;\n\n for(char letter : word2.toCharArray())\n frequency2[letter - \'a\']++;\n\n for(int index=0; index<26; index++){\n if(frequency1[index] == 0 && frequency2[index] != 0)\n return false;\n if(frequency1[index] != 0 && frequency2[index] == 0)\n return false;\n }\n\n Arrays.sort(frequency1);\n Arrays.sort(frequency2);\n\n return Arrays.equals(frequency1, frequency2);\n }\n}\n```\n``` Python []\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n if len(word1) != len(word2):\n return False\n \n frequency1 = [0] * 26\n frequency2 = [0] * 26\n\n for letter in word1:\n frequency1[ord(letter)- ord(\'a\')] += 1\n\n for letter in word2:\n frequency2[ord(letter)- ord(\'a\')] += 1\n\n for index in range (0,26):\n if frequency1[index] == 0 and frequency2[index] != 0:\n return False\n if frequency1[index] != 0 and frequency2[index] == 0:\n return False\n\n return sorted(frequency1) == sorted(frequency2)\n```\n``` Javascript []\nvar closeStrings = function(word1, word2) {\n const frequency1 = new Array(26).fill(0);\n const frequency2 =new Array(26).fill(0);\n\n for(let letter of word1)\n frequency1[letter.charCodeAt(0) - \'a\'.charCodeAt(0)]++;\n\n for(let letter of word2)\n frequency2[letter.charCodeAt(0) - \'a\'.charCodeAt(0)]++;\n\n for(let index=0; index<26; index++){\n if(frequency1[index] == 0 && frequency2[index] != 0)\n return false;\n if(frequency1[index] != 0 && frequency2[index] == 0)\n return false;\n }\n\n frequency1.sort((a, b) => a - b)\n frequency2.sort((a, b) => a - b)\n\n return JSON.stringify(frequency1) === JSON.stringify(frequency2);\n};\n```\n``` Typescript []\nfunction closeStrings(word1: string, word2: string): boolean {\n const frequency1 = new Array(26).fill(0);\n const frequency2 =new Array(26).fill(0);\n\n for(let letter of word1)\n frequency1[letter.charCodeAt(0) - \'a\'.charCodeAt(0)]++;\n\n for(let letter of word2)\n frequency2[letter.charCodeAt(0) - \'a\'.charCodeAt(0)]++;\n\n for(let index=0; index<26; index++){\n if(frequency1[index] == 0 && frequency2[index] != 0)\n return false;\n if(frequency1[index] != 0 && frequency2[index] == 0)\n return false;\n }\n\n frequency1.sort((a, b) => a - b)\n frequency2.sort((a, b) => a - b)\n\n return JSON.stringify(frequency1) === JSON.stringify(frequency2);\n};\n```\n``` C++ []\nclass Solution {\npublic:\n bool closeStrings(std::string word1, std::string word2) {\n std::vector<int> frequency1(26, 0);\n std::vector<int> frequency2(26, 0);\n\n for (char letter : word1)\n frequency1[letter - \'a\']++;\n\n for (char letter : word2)\n frequency2[letter - \'a\']++;\n\n for (int index = 0; index < 26; index++) {\n if (frequency1[index] == 0 && frequency2[index] != 0)\n return false;\n if (frequency1[index] != 0 && frequency2[index] == 0)\n return false;\n }\n\n std::sort(frequency1.begin(), frequency1.end());\n std::sort(frequency2.begin(), frequency2.end());\n\n for (int index = 0; index < 26; index++)\n if (frequency1[index] != frequency2[index])\n return false;\n\n return true;\n }\n};\n```\n``` C# []\npublic class Solution {\n public bool CloseStrings(string word1, string word2) {\n if(word1.Length != word2.Length) return false;\n\n int[] frequency1 = new int[26];\n int[] frequency2 = new int[26];\n\n for(int index=0; index<word1.Length; index++){\n frequency1[word1[index] - \'a\']++;\n frequency2[word2[index] - \'a\']++;\n }\n\n for(int index=0; index<26; index++){\n if(frequency1[index] == 0 && frequency2[index] != 0)\n return false;\n if(frequency1[index] != 0 && frequency2[index] == 0)\n return false;\n }\n\n Array.Sort(frequency1);\n Array.Sort(frequency2);\n\n return frequency1.SequenceEqual(frequency2);\n }\n}\n``` | 8 | 0 | ['String', 'Sorting', 'Counting', 'C++', 'Java', 'TypeScript', 'Python3', 'JavaScript', 'C#'] | 3 |
determine-if-two-strings-are-close | 2 JS solution using objects and Set + filter() | 2-js-solution-using-objects-and-set-filt-3239 | Option 1. I\'m using 2 objects and then compare they keys and values\n\nvar closeStrings = function(word1, word2) {\n\tif (word1.length !== word2.length) return | tania_bir | NORMAL | 2022-12-02T18:04:05.626456+00:00 | 2022-12-02T18:20:38.038618+00:00 | 604 | false | Option 1. I\'m using 2 objects and then compare they keys and values\n```\nvar closeStrings = function(word1, word2) {\n\tif (word1.length !== word2.length) return false;\n\tconst obj1 = {};\n\tconst obj2 = {};\n\n\tfor (let i = 0; i < word1.length; i++) {\n\t\tobj1[word1[i]] = obj1[word1[i]] ? obj1[word1[i]] + 1 : 1;\n\t\tobj2[word2[i]] = obj2[word2[i]] ? obj2[word2[i]] + 1 : 1;\n\t}\n\n\tconst letters = Object.keys(obj1).sort().join("") === Object.keys(obj2).sort().join("");\n\tconst values = Object.values(obj1).sort().join("") === Object.values(obj2).sort().join("");\n\n\treturn letters && values;\n};\n```\nOption 2.\n```\nvar closeStrings = function(word1, word2) {\n if (word1.length !== word2.length) return false;\n \n const arr1 = [];\n const arr2 = [];\n const uniqLetters = [...new Set(word1)]; // get unique letters from the first word to make the loop shorter\n \n for(let i = 0; i < uniqLetters.length; i++) {\n\t // collect sum of every letter in the word\n arr1.push([...word1].filter(letter => letter === uniqLetters[i])?.length);\n arr2.push([...word2].filter(letter => letter === uniqLetters[i])?.length);\n }\n \n if (arr2.includes(0)) return false; // if there is a 0 in the 2nd array it means letters in both words not the same\n \n return arr1.sort().join(\'\') == arr2.sort().join(\'\');\n};\n``` | 8 | 0 | ['JavaScript'] | 1 |
determine-if-two-strings-are-close | SIMPLE PYTHON SOLUTION | simple-python-solution-by-beneath_ocean-ed4g | \nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n lst1=[0]*26\n lst2=[0]*26\n for i in word1:\n l | beneath_ocean | NORMAL | 2022-12-02T03:02:44.300422+00:00 | 2022-12-02T03:02:44.300454+00:00 | 1,708 | false | ```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n lst1=[0]*26\n lst2=[0]*26\n for i in word1:\n lst1[ord(i)-97]+=1\n for i in word2:\n lst2[ord(i)-97]+=1\n for i in range(26):\n if (lst1[i]>0 and lst2[i]==0) or (lst1[i]==0 and lst2[i]>0):\n return False\n lst1.sort()\n lst2.sort()\n if lst1[:]==lst2[:]:\n return True\n return False\n``` | 8 | 0 | ['Array', 'Python', 'Python3'] | 1 |
determine-if-two-strings-are-close | ✅ Easy to understand || C++ Python 🔥 Solution | easy-to-understand-c-python-solution-by-q5du0 | Intuition\n Describe your first thoughts on how to solve this problem. \nEvery occurance and unique character must be same in both the maps.\n\n# Approach\n Des | BruteForce_03 | NORMAL | 2024-01-14T07:53:02.433622+00:00 | 2024-01-14T07:53:02.433656+00:00 | 872 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEvery occurance and unique character must be same in both the maps.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. The function checks if the `lengths` of `word1` and `word2` are `different`. If they are, it immediately returns `false` because words of different lengths cannot be close.\n2. **Frequency Map:**\n - Two maps `(mp1 and mp2)` are created to store the frequency of each character in `word1` and `word2` respectively.\n - A loop iterates through each character in word1 and word2, updating the corresponding frequency in the respective maps.\n\n3. **Building Unique and Frequency Strings:**\n - Two strings `(UniqueWord1 and occUniqueWord1)` are used to store the `unique characters` and their corresponding `frequencies` in `word1`\n - Two similar strings `(UniqueWord2 and occUniqueWord2)` are used for `word2`.\n - Another loop iterates through the frequency maps to build these strings.\n4. **Comparison:**\n - The function checks if the sets of unique characters `(UniqueWord1 and UniqueWord2)` are the same. If they are not, it returns `false`.\n - The frequencies strings `(occUniqueWord1 and occUniqueWord2)` are `sorted`\n - The function then checks if the `sorted` frequency `strings` are the `same`. If they are `not`, it returns `false`.\n5. If all the conditions are met, the function returns `true`, `indicating` that the `two words` are `close`\n \n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(nlogn)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```C++ []\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n\n if(word1.size() != word2.size()) return false;\n\n map<char,int> mp1;\n for(auto it:word1) mp1[it]++;\n \n map<char,int> mp2;\n for(auto it:word2) mp2[it]++;\n\n string UniqueWord1,occUniqueWord1;\n string UniqueWord2,occUniqueWord2;\n \n for(auto it:mp1)\n {\n UniqueWord1+=it.first;\n occUniqueWord1+=to_string(it.second);\n }\n for(auto it:mp2)\n {\n UniqueWord2+=it.first;\n occUniqueWord2+=to_string(it.second);\n }\n\n if(UniqueWord1!=UniqueWord2) return false;\n sort(occUniqueWord1.begin(),occUniqueWord1.end());\n sort(occUniqueWord2.begin(),occUniqueWord2.end());\n if(occUniqueWord1 != occUniqueWord2) return false;\n return true;\n \n }\n};\n```\n```python []\nfrom collections import Counter\n\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n if len(word1) != len(word2):\n return False\n\n count1 = Counter(word1)\n count2 = Counter(word2)\n\n if set(count1.keys()) != set(count2.keys()):\n return False\n\n if sorted(count1.values()) != sorted(count2.values()):\n return False\n\n return True\n\n```\n\n | 7 | 0 | ['Hash Table', 'Sorting', 'Python', 'C++'] | 2 |
determine-if-two-strings-are-close | Beats 99% Easy Solution | beats-99-easy-solution-by-mukul-kumar-jj7z | Intuition\n Describe your first thoughts on how to solve this problem. \nLooking at the test case we just get a intution that the solution lies in the frequency | mukul-kumar | NORMAL | 2024-01-14T05:53:08.142101+00:00 | 2024-01-14T05:53:08.142127+00:00 | 924 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLooking at the test case we just get a intution that the solution lies in the frequency of each character.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe will make two frequency array of each word. and then we will check that for a specific character that if its frequency in word1 if greator than or equal to 1 and zero in the second word. and same for word2. after checking it for this we will sort both of the frequecny array and check the freq of both array to be equal.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nLogn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N);\n# Code\n```\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n if(word1.length() != word2.length()) {\n return false;\n }\n if(word1.equals(word2)) {\n return true;\n }\n int arr1[] = new int[26];\n int arr2[] = new int[26];\n\n for(int i = 0;i<word1.length();i++) {\n arr1[word1.charAt(i) - \'a\']++;\n } \n for(int i = 0;i<word2.length();i++) {\n arr2[word2.charAt(i) - \'a\']++;\n }\n for(int i = 0;i<26;i++) {\n if(arr1[i] >= 1 && arr2[i] == 0) return false;\n else if(arr2[i] >= 1 && arr1[i] == 0) return false;\n }\n Arrays.sort(arr1);\n Arrays.sort(arr2);\n\n for(int i = 0;i<25;i++) {\n if(arr1[i] != arr2[i]) {\n return false;\n }\n }\n return true;\n }\n}\n``` | 7 | 0 | ['String', 'Java'] | 5 |
determine-if-two-strings-are-close | 🔥Python3🔥 Step by Step hints to the answer | python3-step-by-step-hints-to-the-answer-5g0l | Understanding each Operation in the problem is the key to solving this problem, then thinking about if there are any corner cases. \nI made this post to hide ev | MeidaChen | NORMAL | 2022-12-03T03:05:53.049738+00:00 | 2024-01-04T19:29:04.388181+00:00 | 303 | false | Understanding each **Operation** in the problem is the key to solving this problem, then thinking about if there are any **corner cases**. \nI made this post to hide everything first and let you open each hint and think through the problem to solve it yourself. (Code at the end)\n\n<details>\n<summary><strong>Hint1: Operation 1</strong></summary>\n<br/>\n"Operation 1: Swap any two existing characters as many times as necessary."\n\nThis means we can rearrange the word in any order.\n\nTry to rearrange \'abcb\' to \'acdb\' by swapping any two characters as many times as necessary.\n\n</details>\n\n<details>\n<summary><strong>Hint2: Operation 2</strong></summary>\n<br/>\n"Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character."\n\n<strong>This means the frequency of characters in each word needs to be the same.</strong>\n\n```w1 = \'aaabb\'``` is <strong>Close</strong> to ```w1 = \'bbbaa\'``` because we just need to change all ```\'a\'``` to ```\'b\'```, and all ```\'b\'``` to ```\'a\'```.\n\n</details>\n\n<details>\n<summary><strong>Hint3: Corner case</strong></summary>\n<br/>\n\nWhat if a character in ```w1``` is not in ```w2```?\n\n</details>\n\n<details>\n<summary><strong>Algorithm</strong></summary>\n<br/>\nWe will check the following 4 conditions:\n\n(1) frequency of characters in each word is the same.\n\n(2) unique characters in ```w1``` and ```w2``` are the same.\n\n</details>\n\n<details>\n<summary><strong>Code:</strong></summary>\n<br/>\n\n```\nclass Solution:\n def closeStrings(self, w1: str, w2: str) -> bool:\n f1 = Counter(w1)\n f2 = Counter(w2)\n return f1.keys()==f2.keys() and sorted(f1.values()) == sorted(f2.values())\n```\n\n<strong>one-liner</strong>\n```\nclass Solution:\n def closeStrings(self, w1: str, w2: str) -> bool:\n return (f1:=Counter(w1)) and (f2:=Counter(w2)) and len(w1) == len(w2) and f1.keys() == f2.keys() and sorted(f1.values()) == sorted(f2.values())\n```\n\n<strong>Another one-liner</strong>, easy to understand but went through w1, w2 twice.\n```\nclass Solution:\n def closeStrings(self, w1: str, w2: str) -> bool:\n return set(w1) == set(w2) and Counter(Counter(w1).values()) == Counter(Counter(w2).values())\n```\n</details>\n\n**Upvote** if you like this post.\n\n**Connect with me on [LinkedIn](https://www.linkedin.com/in/meida-chen-938a265b/)** if you\'d like to discuss other related topics\n\n\uD83C\uDF1F If you are interested in **Machine Learning** || **Deep Learning** || **Computer Vision** || **Computer Graphics** related projects and topics, check out my **[YouTube Channel](https://www.youtube.com/@meidachen8489)**! Subscribe for regular updates and be part of our growing community. | 7 | 0 | [] | 1 |
determine-if-two-strings-are-close | Java || 5ms 100% || XOR and freq of freq array || No sort, no HashMap || Explanation | java-5ms-100-xor-and-freq-of-freq-array-st7u7 | Steps in the code below:\n\n1) If both strings of different length, then they can never be converted to the same string.\n2) If both strings are identical, then | dudeandcat | NORMAL | 2022-12-02T10:05:09.503419+00:00 | 2022-12-04T23:07:16.115240+00:00 | 975 | false | Steps in the code below:\n\n1) If both strings of different length, then they can never be converted to the same string.\n2) If both strings are identical, then return true without any more work. One test case has strings of length of more than 64_000 characters, with the two strings being identical.\n3) Get the repeat count of each character (i.e. frequency of each character) in both strings.\n4) Find the maximum repeat count of any character in both strings.\n5) If a letter appears in one string, but is not in the other string, then the word strings can never be converted to the same string. This test is done by testing if the frequency count of a letter is zero in one string, but is non-zero in the other string. The implementation of this is by using XOR in the expression `(f1 == 0) ^ (f2 == 0)`. The XOR (^ operator) is true if one of the counts is zero, but the other count is non-zero.\n6) Make sure that the frequency counts from one string, have the exact same frequency counts as the other string, even though these counts may not be in the same order (i.e. the counts may be for different characters). For example, if one string has frequency counts (2,5,3,5) for some arbitrary characters, and the other string has the frequency counts (5,5,3,2), then one string can be converted to the other string. The important thing in this example is that both strings have the same counts, even though the order may be different. Many people\'s solutions to this leetcode problem will sort the arrays of these frequency counts to easily compare the counts. But sorting can be an expensive process in runtime. The code below avoids sorting by using the array `freqFreq[]`, to match each frequence count value. In `freqFreq[]`, for a non-zero frequency count `f1` from the string `word1`, increment `freqFreq[f1]`. For a non-zero frequency count `f2` from the string `word2`, decrement `freqFreq[f2]`. After processing all letters \'a\' to \'z\', if one string can be converted into the other string, then all values in `freqFreq[]` should be zero. Instead of scanning the entire array `freqFreq[]` to check for all zeroes, with a maximum array length of 100_000 values, we use the variable `count` to increment when a `freqFreq[]` values goes from zero to non-zero, and decrement `count` when a `freqFreq[]` value goes from non-zero to zero. Therefore, when all letters have been scanned, the value in `count` should be zero if all values in `freqFreq[]` are zero, and therefore one string can be converted to the other string.\n\nSection 6 above is confusing, so the code for section 6:\n```\n for (int i = \'a\'; i <= \'z\'; i++) {\n int f1 = freq1[i];\n int f2 = freq2[i];\n if ((f1 == 0) ^ (f2 == 0)) return false; // If a char in one string, is not in the other string.\n if (f1 != 0) {\n int f1f = freqFreq[f1]++;\n int f2f = freqFreq[f2]--;\n if (f1f == 0) count++; else if (f1f == -1) count--;\n if (f2f == 0) count++; else if (f2f == 1) count--;\n }\n }\n```\nis illustrated in the graphic below, without the graphic showing the `if...^...` statement covered in section 5 above. The two words have been converted to frequency tables (green arrows), which are counts of how many times each character appears in each word. The `for i` loop processes the frequency tables into the `freqFreq[]` array (blue and red arrows), which is used to test for every frequency value from the first word, having a matching frequency value from the second word, which is a requirement for the two words to be close. Each time a `freqFreq[]` value goes from zero to non-zero, the `count` is incremented. And each time a `freqFreq[]` value goes from non-zero back to zero, the `count` is decremented. At the end, if the words are close, then `freqFreq[]` should be all zeroes, which also means that the `count` value will be zero. If `count` is non-zero, then the words are not close.\n\n\n\nThe following code runs as fast as 5ms, but sometimes as slow as 30ms, in December 2022.\n\nIf useful, please upvote.\n```\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n int n = word1.length();\n if (n != word2.length()) return false; // Not same length strings.\n if (word1.equals(word2)) return true; // Both strings identical.\n\n // Get the count (frequency) of each character in each string.\n int[] freq1 = new int[\'z\' + 1]; // Count of each char in word1\n int[] freq2 = new int[\'z\' + 1]; // Count of each char in word2\n byte[] wordB = new byte[n];\n word1.getBytes(0, n, wordB, 0); // Faster than String.toCharArray().\n for (byte c : wordB) freq1[c]++;\n word2.getBytes(0, n, wordB, 0);\n for (byte c : wordB) freq2[c]++;\n \n // Find highest count for any character.\n int maxFreq = 0;\n for (int i = \'a\'; i <= \'z\'; i++)\n maxFreq = Math.max(maxFreq, Math.max(freq1[i], freq2[i]));\n\n // Make sure that each character in one string exists in the other string, even though \n // the counts of the character in each string is different. For all the counts of \n // characters in each string, make sure there is the same count in the other string, \n // even though the counts may be for different characters.\n byte[] freqFreq = new byte[maxFreq + 1]; // Up/down counters for any frequency \n int count = 0;\n for (int i = \'a\'; i <= \'z\'; i++) {\n int f1 = freq1[i];\n int f2 = freq2[i];\n if ((f1 == 0) ^ (f2 == 0)) return false; // If a char in one string, is not in the other string.\n if (f1 != 0) {\n int f1f = freqFreq[f1]++;\n int f2f = freqFreq[f2]--;\n if (f1f == 0) count++; else if (f1f == -1) count--;\n if (f2f == 0) count++; else if (f2f == 1) count--;\n }\n }\n return count == 0; // Return true only if the counts of characters are the same in \n // both strings.\n }\n}\n```\n--------------------------------------------\nAnother version of code that runs equally fast at 5ms, is shown below. I got the original code from user Vezzz, then modified Vezzz\'s code to try to make it faster, but I could not reduce the code\'s fastest runtime. The code below is my modified version of the code. It uses insertion sorts on the frequency count arrays, then compares the two arrays for being identical. The Vezzz\'s self-coded insertion sorts appear to be faster than the `Arrays.sort()` used my many other people\'s solutions. An improvement I also picked up from Vezzz\'s code is the use of the `getBytes(int, int, array, int)` method, which seems much faster than the `String.toCharArray()` method I had been using, and reduced my original code\'s runtime by nearly 50%.\n```\nclass Solution { // Vezzz\n public boolean closeStrings(String word1, String word2) {\n int n = word1.length();\n if (n != word2.length()) return false;\n if (word1.equals(word2)) return true;\n\n // Get the counts of each letter in the two strings\n int freq1[] = new int[\'z\' + 1];\n int freq2[] = new int[\'z\' + 1];\n byte[] w = new byte[n];\n word1.getBytes(0, n, w, 0);\n for (byte c : w) freq1[c]++;\n word2.getBytes(0, n, w, 0);\n for (byte c : w) freq2[c]++;\n\n // Make sure the same letters are used in both strings, \n // with the count of chars NOT being compared.\n for (int i = \'a\'; i <= \'z\'; i++)\n if (freq1[i] == 0 ^ freq2[i] == 0)\n return false;\n\n // Insertion-sort the counts of letters from string #1.\n freq1[\'a\' - 1] = -1;\n for (int i, k = \'a\'; ++k <= \'z\';) {\n int f1i = freq1[i = k];\n while (f1i < freq1[--i]) freq1[i + 1] = freq1[i];\n freq1[i + 1] = f1i;\n }\n\n // Insertion-sort the counts of letters from string #2.\n freq2[\'a\' - 1] = -1;\n for (int i, k = \'a\'; ++k <= \'z\';) {\n int f2i = freq2[i = k];\n while (f2i < freq2[--i]) freq2[i + 1] = freq2[i];\n freq2[i + 1] = f2i;\n }\n\n // Make sure sorted counts are the same for both strings.\n for (int i = \'a\'; i <= \'z\'; i++)\n if (freq1[i] != freq2[i])\n return false;\n return true;\n }\n}\n```\n | 7 | 0 | ['Java'] | 1 |
determine-if-two-strings-are-close | Python straight forward O(N) solution | python-straight-forward-on-solution-by-k-2qo2 | Important testcase\nMost of you would probably overlook this edge case:\nword1 = uau & word2 = ssx\n\nclass Solution:\n def closeStrings(self, word1: str, wo | kevinjm17 | NORMAL | 2022-12-02T09:11:30.539960+00:00 | 2023-06-01T13:47:49.855697+00:00 | 1,361 | false | # Important testcase\nMost of you would probably overlook this edge case:\nword1 = uau & word2 = ssx\n```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n if len(word1) != len(word2):\n return False\n\n count1, count2 = {}, {}\n for i in range(len(word1)):\n count1[word1[i]] = count1.get(word1[i], 0) + 1\n count2[word2[i]] = count2.get(word2[i], 0) + 1\n\n return sorted(count1.values()) == sorted(count2.values()) and set(word1) == set(word2)\n```\n# Please upvote if you find this helpful. | 7 | 0 | ['Hash Table', 'Sorting', 'Python3'] | 1 |
determine-if-two-strings-are-close | Easy Explain | Optimized O(N) | CPP | Array | easy-explain-optimized-on-cpp-array-by-b-7j8o | Approach\nIdea : Two thing\'s Need to check \n\nUse normal array to reduce time complexcity into O(Nlog N) to O(N)\n\n- Frequency of Char need\'s to be same the | bhalerao-2002 | NORMAL | 2022-12-02T01:50:48.529507+00:00 | 2022-12-02T01:50:48.529562+00:00 | 990 | false | # Approach\nIdea : Two thing\'s Need to check \n\nUse normal array to reduce time complexcity into O(Nlog N) to O(N)\n\n- Frequency of Char need\'s to be same there both of string as we can do Transform every occurrence of one existing character into another existing character\n- All the unique char which there in String1 need\'s to there as well In string2\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# CPP Code\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n vector<int>w1(26,0),w2(26,0),w3(26,0),w4(26,0);\n for(char c:word1)\n w1[c-\'a\']++,w3[c-\'a\'] = 1;\n \n for(char c:word2)\n w2[c-\'a\']++,w4[c-\'a\'] = 1;\n \n sort(begin(w1),end(w1));\n sort(begin(w2),end(w2));\n return w1==w2&&w3==w4;\n }\n};\n```\n#Upvote\nThank You :) | 7 | 1 | ['C++'] | 2 |
determine-if-two-strings-are-close | Swift: Determine if Two Strings Are Close (+ Test Cases) | swift-determine-if-two-strings-are-close-zolb | swift\nclass Solution {\n func closeStrings(_ word1: String, _ word2: String) -> Bool {\n typealias US = UnicodeScalar\n let az = ((US("a").val | AsahiOcean | NORMAL | 2021-07-03T23:51:48.676329+00:00 | 2021-07-03T23:51:48.676360+00:00 | 1,150 | false | ```swift\nclass Solution {\n func closeStrings(_ word1: String, _ word2: String) -> Bool {\n typealias US = UnicodeScalar\n let az = ((US("a").value...US("z").value).map{US($0)})\n let array = Array(repeating: 0, count: az.count)\n var c1 = array, c2 = array\n word1.forEach{c1[Int($0.asciiValue!) - 97] += 1}\n word2.forEach{c2[Int($0.asciiValue!) - 97] += 1}\n for i in az.indices {\n if c1[i] > 0 && c2[i] == 0 { return false }\n if c2[i] > 0 && c1[i] == 0 { return false }\n }\n c1.sort()\n c2.sort()\n return c1 == c2\n }\n}\n```\n\n```swift\nimport XCTest\n\n// Executed 4 tests, with 0 failures (0 unexpected) in 0.186 (0.188) seconds\n\nclass Tests: XCTestCase {\n private let s = Solution()\n func test1() {\n let result = s.closeStrings("abc", "bca")\n XCTAssertEqual(result, true)\n }\n func test2() {\n let result = s.closeStrings("a", "aa")\n XCTAssertEqual(result, false)\n }\n func test3() {\n let result = s.closeStrings("cabbba", "abbccc")\n XCTAssertEqual(result, true)\n }\n func test4() {\n let result = s.closeStrings("cabbba", "aabbss")\n XCTAssertEqual(result, false)\n }\n}\n\nTests.defaultTestSuite.run()\n``` | 7 | 0 | ['Swift'] | 1 |
determine-if-two-strings-are-close | ✅ One Line Solution | one-line-solution-by-mikposp-6ulj | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly. PEP 8 is violated intentionally)\n\n# Code #1 - The | MikPosp | NORMAL | 2024-01-14T11:41:07.003045+00:00 | 2024-01-14T19:37:06.937966+00:00 | 758 | false | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly. PEP 8 is violated intentionally)\n\n# Code #1 - The Most Concise\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def closeStrings(self, w1: str, w2: str) -> bool:\n return (f:=lambda w:(set(w),sorted(Counter(w).values())))(w1)==f(w2)\n```\n\n# Code #2 - No Additional Set, Counting Instead of Sorting\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def closeStrings(self, w1: str, w2: str) -> bool:\n return (f:=lambda w:((c:=Counter(w)).keys(),Counter(c.values())))(w1)==f(w2)\n```\n\n# Code #3 - Simple, Walrus Free\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def closeStrings(self, w1: str, w2: str) -> bool:\n return set(w1)==set(w2) and sorted(Counter(w1).values())==sorted(Counter(w2).values())\n``` | 6 | 0 | ['Hash Table', 'String', 'Sorting', 'Counting', 'Python', 'Python3'] | 0 |
determine-if-two-strings-are-close | beginner friendly beats 97% simple hashing | beginner-friendly-beats-97-simple-hashin-1lvl | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nsimple hashing\n1. stor | sukuna_27 | NORMAL | 2024-01-14T10:18:31.183614+00:00 | 2024-01-14T10:18:31.183647+00:00 | 511 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nsimple hashing\n1. store every character of string in a hash array\n2. if some character appears in first hash array and not in second array than its not possible to make strings close\n3. **also check if freq is different for different characters in both arrays by first sorting both of them** \n\n# Complexity\n- Time complexity:O(n+m)\n- as sorting of only 26 elements wont take that much time\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n int hash1[26]={0};\n int hash2[26]={0};\n if(word1.size()!=word2.size())return false;\n for(int i=0;i<word1.size();i++){\n hash1[word1[i]-97]++;\n }\n for(int i=0;i<word2.size();i++){\n hash2[word2[i]-97]++;\n }\n int total1=0;\n int total2=0;\n for(int i=0;i<26;i++){\n if(hash1[i]==0&&hash2[i]!=0||hash1[i]!=0&&hash2[i]==0)return false;\n }\n sort(hash1,hash1+26);\n sort(hash2,hash2+26);\n for(int i=0;i<26;i++){\n if(hash1[i]!=hash2[i])return false;\n }\n return true;\n }\n};\n``` | 6 | 0 | ['Hash Table', 'C++'] | 2 |
determine-if-two-strings-are-close | Beats 80% in RunTime | beats-80-in-runtime-by-abdelrhmankaram-fb7y | Approach\nUsing Frequency array and bit manipulation.\n\nFrequency array\n- get the frequency for each character then compine the frequencies in two sets one fo | abdelrhmankaram | NORMAL | 2024-01-14T00:30:51.069651+00:00 | 2024-01-14T00:33:45.348251+00:00 | 370 | false | # Approach\nUsing **$$Frequency array$$** and **$$bit manipulation$$**.\n\n**Frequency array**\n- get the frequency for each character then compine the frequencies in two sets one for each word.\n- if the two sets are equal and the two words have the same characters then they are close.\n\n**Bit manipulation**\n- record the presence of each charcter in a bit in every mask.\n- the bit index is determined by the alphabetical order corresponding to character \'a\' by **char - \'a\'**.\n- if two masks are equal, then the two words have the same characters.\n\n# Complexity\n- Time complexity:\n sort complexity is **O(26 log(26))** so it\'s typically a **O(1)** + traversal over the strings is **O(N)**.\n- Space complexity:\n **O(N)**.\n\n# Code\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n if(word1.size() != word2.size()){\n return false;\n }\n\n int mask1 = 0, mask2 = 0;\n vector<int> fre1(26), fre2(26);\n\n for(int i = 0 ; i < word1.size() ; i++){\n mask1 |= (1 << word1[i] - \'a\');\n mask2 |= (1 << word2[i] - \'a\');\n fre1[word1[i] - \'a\']++;\n fre2[word2[i] - \'a\']++;\n }\n\n vector<int> vec1, vec2;\n\n for(int i = 0 ; i < 26 ; i++){\n if(fre1[i])vec1.push_back(fre1[i]);\n if(fre2[i])vec2.push_back(fre2[i]);\n }\n\n sort(vec1.begin(), vec1.end()); sort(vec2.begin(), vec2.end());\n return vec1 == vec2 && mask1 == mask2;\n }\n};\n``` | 6 | 0 | ['C++'] | 0 |
determine-if-two-strings-are-close | 🚀 Fastest and easiest solution (С++, O(n), 27 ms) | fastest-and-easiest-solution-s-on-27-ms-ufnso | To determine that strings are close, we can distinguish three rules that word1 and word2 must satisfy:\n1. The lengths of word1 and word2 must be equal.\n2. Bot | d9rs | NORMAL | 2022-12-02T11:30:44.975361+00:00 | 2022-12-02T14:20:08.584955+00:00 | 346 | false | **To determine that strings are close, we can distinguish three rules that `word1` and `word2` must satisfy:**\n1. The lengths of `word1` and `word2` must be equal.\n2. Both strings must consist of the same unique characters, because we cannot change a string character to another that is not in the string.\n3. The frequency of characters in both strings must be the same. For example, if `word1` = `abbc` (character frequency: `a` = 1, `b` = 2, `c` = 1) and `word2` = `aabc` (character frequency: `a` = 2, `b` = 1, `c` = 1), sort the resulting frequencies and we have the same array `[1, 1, 2]`, which means that we can convert the existing characters to make the strings equal (in this example we must convert the character `a` to `b`).\n\nHow can we check the above rules?\n1. **Just check if `word1.size()` and `word2.size()` are equal or not.**\n2. The very first thing that comes to mind to test this rule is to use a set (hash set) or even better an array, since we have only 26 characters in the alphabet. **However, there is an even cooler idea - use a bitmask of unique characters for each string!** This is the best solution, because bitmasks are much faster and checking their equality is much easier and more efficient.\n3. The third rule can be checked in different ways, also using hash tables or arrays as hash tables. I prefer arrays in this case because they are very small. **We can have an array as a hash table for each string, count the frequency of occurrence of each character, sort the resulting arrays, and simply compare them**.\n\nImplementation of the above solution in C++:\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n\t // just an optimization trick, if you want 100% you should use it\n ios::sync_with_stdio(false);\n cin.tie(0);\n \n if (word1.size() != word2.size()) {\n return false;\n }\n \n int a[26] = {0}, b[26] = {0}, mask1 = 0, mask2 = 0;\n \n for (int i = 0; i < word1.size(); i++) {\n a[word1[i] - \'a\']++;\n b[word2[i] - \'a\']++;\n mask1 |= 1 << (word1[i] - \'a\');\n mask2 |= 1 << (word2[i] - \'a\');\n };\n \n\t\t// you can also use here (mask1 ^ mask2) != 0, mask1 - mask2 != 0 and so on\n if (mask1 != mask2) {\n return false;\n }\n \n sort(begin(a), end(a));\n sort(begin(b), end(b));\n \n for (int i = 0; i < 26; i++) {\n if (a[i] != b[i]) return false;\n }\n \n return true;\n }\n};\n```\n**Complexity:** O(n). **I got 27 ms the first time I submitted this solution.** | 6 | 0 | ['Array', 'C', 'Bitmask'] | 2 |
determine-if-two-strings-are-close | ✅[C++]|| O(N) || Easiest || Beginner-Friendly | c-on-easiest-beginner-friendly-by-ajaymi-1pgd | Intuition : Store char and count of chars of each char of both the strings into 2 \n\t\t\t\t\t\tdifferent maps. \n\t\t\t\t\t\tSince map store value in ascendin | ajaymishra | NORMAL | 2022-12-02T08:49:59.733241+00:00 | 2022-12-02T08:49:59.733280+00:00 | 882 | false | **Intuition :** Store char and count of chars of each char of both the strings into 2 \n\t\t\t\t\t\tdifferent maps. \n\t\t\t\t\t\tSince map store value in ascending order.\n\t\t\t\t\t\tAfter storing values in maps check if map1->first == map2->first\n\t\t\t\t\t\tthis will help us in checking wether char are equal or not .\n\t\t\t\t After that push the count of the of each char in vector \n\t\t\t\t\t\tthen sort the vector and check they are equal or not.\n\n\n\n```\nclass Solution\n{\n public:\n bool closeStrings(string word1, string word2)\n {\n int n = word1.size(); //to store the size of word1\n int m = word2.size(); //to store the size of word2\n \n vector<int> v1;\n vector<int> v2;\n\n map<char, int> mp1, mp2;\n \n \n if (n != m) // checking wether 2 strings have same size or not\n return false;\n \n for (int i = 0; i < n; i++) //storing char and count of each char\n {\n mp1[word1[i]]++;\n }\n for (int i = 0; i < m; i++)\n {\n mp2[word2[i]]++;\n }\n\n if (mp1.size() != mp2.size()) \n return false;\n\n map<char, int>::iterator it1 = mp1.begin();\n map<char, int>::iterator it2 = mp2.begin();\n\n while (it1 != mp1.end())\n {\n if (it1->first == it2->first)\n it1++, it2++;\n else\n return false;\n }\n\n for (auto i: mp1)\n {\n v1.push_back(i.second);\n }\n for (auto i: mp2)\n {\n v2.push_back(i.second);\n }\n\n sort(v1.begin(), v1.end());\n sort(v2.begin(), v2.end());\n\n if (v1 == v2)\n return true;\n return false;\n }\n};\n\n//This approach is beginner friendly so a newbie can also understand.\n\t\t\t\t\t\t\t\t\t\t\t:) | 6 | 0 | ['String', 'C', 'C++'] | 1 |
determine-if-two-strings-are-close | Easy Approach || C++ || Hashing + Sorting | easy-approach-c-hashing-sorting-by-upadh-xs88 | Intuition\nSince we can swap any character any number of times we could sort. And we can swap the characters in the given string for freq match so we just have | upadhyayabhi0107 | NORMAL | 2022-12-02T06:29:01.642187+00:00 | 2022-12-02T06:29:01.642232+00:00 | 514 | false | # Intuition\nSince we can swap any character any number of times we could sort. And we can swap the characters in the given string for freq match so we just have to match freq. \n\n# Approach\nSimple Approach :\n- Base case : if words size doesn\'t match we directly return false\n- Base case 2 : If words themselves don\'t match we can return false\n- We\'ll make a freq map or freq count and then well just check wheather the freq are same or not.\n\n# Complexity\n- Time complexity: O(NLogN) since we are sorting\n\n- Space complexity: O(N) extra space for frq count\n\n# Code\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n if(word1.size() != word2.size()) return false;\n vector<int> v(26 , 0) , v1(26 , 0);\n for(auto it : word1){\n v[it - \'a\']++;\n }\n for(auto it : word2){\n v1[it - \'a\']++;\n }\n sort(v.begin() , v.end());\n sort(v1.begin() , v1.end());\n reverse(v.begin() , v.end());\n reverse(v1.begin() , v1.end());\n if(set(word1.begin(),word1.end())!=\n set(word2.begin(),word2.end()))\n return false;\n for(int i = 0 ; i< 26 ; i++){\n if(v[i] != v1[i])return false;\n }\n return true;\n }\n};\n``` | 6 | 0 | ['Hash Table', 'Sorting', 'Counting', 'C++'] | 0 |
determine-if-two-strings-are-close | 🗓️ Daily LeetCoding Challenge December, Day 2 | daily-leetcoding-challenge-december-day-uln4o | This problem is the Daily LeetCoding Challenge for December, Day 2. Feel free to share anything related to this problem here! You can ask questions, discuss wha | leetcode | OFFICIAL | 2022-12-02T00:00:20.237888+00:00 | 2022-12-02T00:00:20.237959+00:00 | 5,674 | false | This problem is the Daily LeetCoding Challenge for December, Day 2.
Feel free to share anything related to this problem here!
You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made!
---
If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide
- **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem.
- **Images** that help explain the algorithm.
- **Language and Code** you used to pass the problem.
- **Time and Space complexity analysis**.
---
**📌 Do you want to learn the problem thoroughly?**
Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/determine-if-two-strings-are-close/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis.
<details>
<summary> Spoiler Alert! We'll explain these 3 approaches in the official solution</summary>
**Approach 1:** Using HashMap
**Approach 2:** Using Frequency Array Map
**Approach 3:** Using Bitwise Operation and Frequency Array Map
</details>
If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)!
---
<br>
<p align="center">
<a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank">
<img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" />
</a>
</p>
<br> | 6 | 0 | [] | 64 |
determine-if-two-strings-are-close | [C++][Microsoft] - Simple and easy to understand | cmicrosoft-simple-and-easy-to-understand-ggse | \nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n int len=word1.length();\n if(word2.length()!=len)\n | morning_coder | NORMAL | 2021-01-25T11:10:27.130556+00:00 | 2021-01-25T11:10:27.130632+00:00 | 794 | false | ```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n int len=word1.length();\n if(word2.length()!=len)\n return false;\n \n vector<int> count1(26,0);\n vector<int> count2(26,0);\n for(int i=0;i<len;i++){\n count1[word1[i]-\'a\']++;\n count2[word2[i]-\'a\']++;\n }\n //Checking if same characters exist\n for(int i=0;i<26;i++){\n if((count1[i]>0 && count2[i]==0) || (count1[i]==0 && count2[i]>0))\n return false;\n }\n sort(begin(count1),end(count1));\n sort(begin(count2),end(count2));\n for(int i=0;i<26;i++){\n if(count1[i]!=count2[i])\n return false;\n }\n return true;\n }\n};\n``` | 6 | 0 | ['C', 'C++'] | 0 |
determine-if-two-strings-are-close | simple cpp solution beats 98% :) | simple-cpp-solution-beats-98-by-yash_pal-qcgu | i have created two hash function to count the number of occurance of all char in word1 and word2\noccording to 1st rule : we can swap any two char at any number | yash_pal2907 | NORMAL | 2020-11-19T04:13:31.914966+00:00 | 2020-11-19T04:13:31.914996+00:00 | 479 | false | i have created two hash function to count the number of occurance of all char in word1 and word2\noccording to 1st rule : we can swap any two char at any number of time so if the cnt of all char in string word1 and word2 is same then string will be accepted .(there must not present any new char in word2 that is not present in word1)\non aplying 2nd rule : we can change the we can convert one char into other . so if any two charcter frequncy is difference then if possible then convert them .\n\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n if(word1.length()!=word2.length())\n return false;\n vector<int> hash1(26,0);\n vector<int> hash2(26,0);\n for(int i=0;i<word1.length();i++){\n hash1[word1[i] - \'a\']++;\n }\n for(int i=0;i<word2.length();i++){\n if(hash1[word2[i]-\'a\']==0) //cheking for new char present in word2 (new char means that is not present in word1)\n return false;\n hash2[word2[i]-\'a\']++;\n }\n sort(hash1.begin(), hash1.end()); // for 2nd rule matching\n sort(hash2.begin(), hash2.end());\n for(int i=0;i<26;i++){\n if(hash1[i]!=hash2[i]) // condition where we can\'t convert char\n return false;\n }\n return true;\n }\n};\n``` | 6 | 0 | ['Hash Function', 'C++'] | 0 |
determine-if-two-strings-are-close | [Python3] Concise Solution | python3-concise-solution-by-kunqian-0-thbq | python\ndef closeStrings(self, word1: str, word2: str) -> bool:\n\tif len(word1) != len(word2):\n\t\treturn False\n\tc1, c2 = Counter(word1), Counter(word2)\n\t | kunqian-0 | NORMAL | 2020-11-15T04:08:18.019064+00:00 | 2020-11-15T04:08:18.019114+00:00 | 310 | false | ```python\ndef closeStrings(self, word1: str, word2: str) -> bool:\n\tif len(word1) != len(word2):\n\t\treturn False\n\tc1, c2 = Counter(word1), Counter(word2)\n\treturn c1.keys() == c2.keys() and sorted(c1.values()) == sorted(c2.values())\n``` | 6 | 4 | [] | 1 |
determine-if-two-strings-are-close | Easy solution with 4 different approaches || Explained why TC is O(n) | easy-solution-with-4-different-approache-vkou | Approach 1: Sorting (Frequency Count + Character Set)Idea:
Two words can be transformed into each other if they:
Have the same set of unique characters.
Have t | princebhayani | NORMAL | 2025-02-14T09:09:20.445591+00:00 | 2025-02-14T09:45:36.813734+00:00 | 587 | false | ## **Approach 1: Sorting (Frequency Count + Character Set)**
### **Idea:**
- Two words can be transformed into each other if they:
1. Have the **same set of unique characters**.
2. Have **the same frequency distribution** (order doesn’t matter).
### **Steps:**
1. **Count the frequency** of each character in both strings.
2. **Check if both words have the same unique characters**.
3. **Sort both frequency arrays** and compare them.
### **Time Complexity:**
- **O(N)** for counting characters.
- **O(1) (O(26 log 26))** for sorting (since there are only 26 characters).
- **Overall: O(N)**.
### **Java Code with Comments**
```java
class Solution {
public boolean closeStrings(String word1, String word2) {
// If the lengths are different, they can never be "close"
if (word1.length() != word2.length()) return false;
// Frequency arrays for both words
int[] freq1 = new int[26];
int[] freq2 = new int[26];
// Populate frequency arrays
for (char c : word1.toCharArray()) freq1[c - 'a']++;
for (char c : word2.toCharArray()) freq2[c - 'a']++;
// Check if both words have the same unique characters
for (int i = 0; i < 26; i++) {
if ((freq1[i] > 0) != (freq2[i] > 0)) return false;
}
// Sort frequency arrays and compare them
Arrays.sort(freq1);
Arrays.sort(freq2);
return Arrays.equals(freq1, freq2);
}
}
```
---
## **Approach 2: HashMap (Counting Frequency Distribution)**
### **Idea:**
- Instead of sorting, use **HashMaps** to:
- Store **character frequencies**.
- Store **how many times each frequency appears**.
### **Steps:**
1. **Count the frequency** of each character using HashMaps.
2. **Ensure both words have the same character set**.
3. **Compare the frequency distributions**.
### **Time Complexity:**
- **O(N)** for counting characters.
- **O(N)** for comparing frequency distributions.
- **Overall: O(N)**.
### **Java Code with Comments**
```java
class Solution {
public boolean closeStrings(String word1, String word2) {
if (word1.length() != word2.length()) return false;
// HashMap to store character frequencies
HashMap<Character, Integer> freq1 = new HashMap<>();
HashMap<Character, Integer> freq2 = new HashMap<>();
// Count frequencies for word1
for (char c : word1.toCharArray()) freq1.put(c, freq1.getOrDefault(c, 0) + 1);
// Count frequencies for word2
for (char c : word2.toCharArray()) freq2.put(c, freq2.getOrDefault(c, 0) + 1);
// Check if both words contain the same set of characters
if (!freq1.keySet().equals(freq2.keySet())) return false;
// HashMap to store the count of frequencies
HashMap<Integer, Integer> countMap1 = new HashMap<>();
HashMap<Integer, Integer> countMap2 = new HashMap<>();
// Count how many times each frequency appears
for (int val : freq1.values()) countMap1.put(val, countMap1.getOrDefault(val, 0) + 1);
for (int val : freq2.values()) countMap2.put(val, countMap2.getOrDefault(val, 0) + 1);
// If frequency distributions match, return true
return countMap1.equals(countMap2);
}
}
```
---
## **Approach 3: Frequency Buckets (Optimized Array Approach)**
### **Idea:**
Instead of HashMaps, use:
- **One array** for character frequencies.
- **Another array** to store how many times each frequency appears.
### **Java Code with Comments**
```java
class Solution {
public boolean closeStrings(String word1, String word2) {
if (word1.length() != word2.length()) return false;
int[] freq1 = new int[26];
int[] freq2 = new int[26];
// Populate frequency arrays
for (char c : word1.toCharArray()) freq1[c - 'a']++;
for (char c : word2.toCharArray()) freq2[c - 'a']++;
// Check if both words have the same unique characters
for (int i = 0; i < 26; i++) {
if ((freq1[i] > 0) != (freq2[i] > 0)) return false;
}
// Frequency bucket arrays
int[] bucket1 = new int[word1.length() + 1];
int[] bucket2 = new int[word2.length() + 1];
// Count occurrences of each frequency
for (int i = 0; i < 26; i++) {
bucket1[freq1[i]]++;
bucket2[freq2[i]]++;
}
return Arrays.equals(bucket1, bucket2);
}
}
```
---
## **Approach 4: Bit Manipulation (Optimized for Character Set Comparison)**
### **Idea:**
- Use **bitwise operations** to track character presence.
- Use **arrays** for frequency counts.
### **Java Code with Comments**
```java
class Solution {
public boolean closeStrings(String word1, String word2) {
if (word1.length() != word2.length()) return false;
int bitset1 = 0, bitset2 = 0;
int[] freq1 = new int[26];
int[] freq2 = new int[26];
// Populate frequency arrays and bitsets
for (char c : word1.toCharArray()) {
bitset1 |= (1 << (c - 'a')); // Mark character presence
freq1[c - 'a']++;
}
for (char c : word2.toCharArray()) {
bitset2 |= (1 << (c - 'a')); // Mark character presence
freq2[c - 'a']++;
}
// If character sets are different, return false
if (bitset1 != bitset2) return false;
// Sort frequency arrays and compare
Arrays.sort(freq1);
Arrays.sort(freq2);
return Arrays.equals(freq1, freq2);
}
}
```
---
## **Comparison of Approaches**
| Approach | Data Structure Used | Time Complexity | Space Complexity |
|----------|------------------|---------------|----------------|
| **Sorting Approach** | Arrays + Sorting | O(N) | O(1) |
| **HashMap Approach** | HashMaps | O(N) | O(N) |
| **Frequency Bucket Approach** | Arrays | O(N) | O(N) |
| **Bit Manipulation Approach** | Bitwise + Arrays | O(N) | O(1) |
### **Best Approach:**
- **Bit Manipulation Approach** is the most efficient as it uses bitwise operations, making it optimal in both time and space.
---
Now you might question on time complexity why it's O(N) not O(NlogN)
Here is Explanation:
**Sorting an array of size \( n \) typically takes \( O(n log n) \), not \( O(n) \).**
However, in **this specific case**, we are sorting **a fixed-size array of length 26** (since we only have lowercase English letters).
### **Why is Sorting O(1) here?**
1. **The array size is constant (26 elements).**
- Sorting an array of 26 elements is **effectively a constant-time operation**.
- Even if sorting is normally \( O(n log n) \), here \( n = 26 \), making it **insignificant** in complexity analysis.
2. **Sorting is treated as O(1) (constant time) for small fixed-size inputs.**
- Since 26 is a **constant**, sorting it **does not scale with input size**.
- For **large inputs (word length = 10⁵)**, sorting 26 elements is negligible.
### **Final Complexity Breakdown**
| Step | Complexity |
|------|------------|
| Counting character frequencies | \( O(N) \) |
| Checking unique characters | \( O(26) = O(1) \) |
| Sorting the frequency array | \( O(26 log 26) = O(1) \) |
| Comparing arrays | \( O(26) = O(1) \) |
| **Total Complexity** | \( O(N) + O(1) = O(N) \) |
So while **sorting is normally \( O(n log n) \)**, in this problem, since **n is at most 26**, it's effectively **O(1)**.
Thus, the overall complexity remains **O(N)**.
---
### **Alternative Explanation:**
If sorting were applied to **all characters in the entire word (instead of just 26 unique ones)**, then:
- Sorting would be **O(N log N)**.
- The overall complexity would be **O(N log N)** instead of **O(N)**.
But since we're only sorting a **fixed-size array (26)**, we **ignore it** in Big-O notation.
Hope this clears it up! 🚀 | 5 | 0 | ['Hash Table', 'String', 'Bit Manipulation', 'Sorting', 'Counting', 'Hash Function', 'Bitmask', 'Java'] | 0 |
determine-if-two-strings-are-close | ✅☑Beats 100% Users | Beginner Friendly | 4 lines Easy Solution | Fully Explained 🔥🔥 | beats-100-users-beginner-friendly-4-line-krxp | Intuition\n Describe your first thoughts on how to solve this problem. \nLooking at the test case we just get a intution that the solution lies in the frequency | MindOfshridhar | NORMAL | 2024-01-14T13:42:02.105002+00:00 | 2024-01-14T13:42:02.105020+00:00 | 426 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Looking at the test case we just get a intution that the solution lies in the frequency of each character.**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Create character count dictionaries c1 and c2 for input strings w1 and w2.**\n2. **Create count dictionaries n1 and n2 for unique counts in c1 and c2.**\n3. **Return True if either:\n => Character counts are identical (c1 == c2).\n => Count of counts is the same, and the sets of characters are the same (n1 == n2 and set(w1) == set(w2)).**\n\n\n# Complexity\n- Time complexity: O(len(w1) + len(w2))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(len(w1) + len(w2))\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n# Code\n```\nclass Solution:\n def closeStrings(self, w1: str, w2: str) -> bool:\n c1,c2= Counter(w1),Counter(w2)\n\n n1 = Counter([v for v in c1.values()])\n n2 = Counter([v for v in c2.values()])\n\n return c1 == c2 or (n1==n2 and set(w1) == set(w2))\n```\n | 5 | 0 | ['Hash Table', 'Counting', 'Python', 'Python3'] | 1 |
determine-if-two-strings-are-close | ✅✅🔥Beats 99.84% With Proof | Very Easy to Understand | Intuitive Approach ✅✅🔥 | beats-9984-with-proof-very-easy-to-under-0fft | Proof\n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nTo determine if two strings are close, we need to check if they can be tra | areetrahalder | NORMAL | 2024-01-14T09:28:15.010521+00:00 | 2024-01-14T09:28:15.010549+00:00 | 767 | false | # Proof\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo determine if two strings are close, we need to check if they can be transformed into each other using the given operations. We can approach this problem by counting the occurrences of each character in both strings and checking if the set of characters is the same for both strings.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Check if the lengths of both strings are equal. If not, return false, as strings of different lengths cannot be transformed into each other.\n2. Check if the strings are already equal. If so, return true, as no operations are needed.\n3. Count the occurrences of each character in both strings and store them in arrays `firstSet` and `secondSet`.\n4. Check if the set of characters (non-zero counts) is the same for both strings. If not, return false.\n5. Sort both arrays to compare the frequencies of characters.\n6. Compare the sorted arrays element by element. If any element is different, return false.\n7. If all elements are the same, return true.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n> where n is the length of the input strings. This is due to the sorting step.\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n> since the size of the character arrays is constant (26 characters).\n\n# Code\n```Java []\nclass Solution {\n public boolean closeStrings(String w1, String w2) {\n int i = 0, l1 = w1.length(), l2 = w2.length();\n if(l1 != l2) return false;\n if(w1.equals(w2)) return true;\n int[] firstSet=new int[26];\n int[] secondSet=new int[26];\n char ch; \n while(i<l1){\n ch = w1.charAt(i++);\n firstSet[ch-\'a\']++;\n }\n i = 0;\n while(i<l2){\n ch = w2.charAt(i++);\n if(firstSet[ch-\'a\'] == 0) return false;\n secondSet[ch-\'a\']++;\n }\n Arrays.sort(firstSet);\n Arrays.sort(secondSet);\n i = 25; \n while(i > -1 && firstSet[i] != 0){\n if(firstSet[i] != secondSet[i--]){\n return false;\n }\n }\n return true;\n }\n}\n```\n```C []\nbool closeStrings(char* word1, char* word2) {\n int i = 0, l1 = strlen(word1), l2 = strlen(word2);\n \n // Check if the lengths of both strings are equal\n if (l1 != l2) return false;\n\n // Check if the strings are already equal\n if (strcmp(word1, word2) == 0) return true;\n\n int* firstSet = (int*)calloc(26, sizeof(int));\n int* secondSet = (int*)calloc(26, sizeof(int));\n char ch;\n\n // Count occurrences in word1\n while (i < l1) {\n ch = word1[i++];\n firstSet[ch - \'a\']++;\n }\n\n i = 0;\n\n // Count occurrences in word2 and check if characters are in word1\n while (i < l2) {\n ch = word2[i++];\n if (firstSet[ch - \'a\'] == 0) {\n free(firstSet);\n free(secondSet);\n return false;\n }\n secondSet[ch - \'a\']++;\n }\n\n // Sort both arrays\n qsort(firstSet, 26, sizeof(int), compare);\n qsort(secondSet, 26, sizeof(int), compare);\n\n // Compare the sorted arrays element by element\n for (i = 0; i < 26; i++) {\n if (firstSet[i] != secondSet[i]) {\n free(firstSet);\n free(secondSet);\n return false;\n }\n }\n\n free(firstSet);\n free(secondSet);\n return true;\n}\n```\n```C++ []\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n int l1 = word1.length(), l2 = word2.length();\n \n // Step 1: Check if lengths are equal\n if (l1 != l2) {\n return false;\n }\n \n // Step 2: Check if strings are already equal\n if (word1 == word2) {\n return true;\n }\n \n // Step 3: Count occurrences of each character\n vector<int> firstSet(26, 0), secondSet(26, 0);\n \n for (char ch : word1) {\n firstSet[ch - \'a\']++;\n }\n \n for (char ch : word2) {\n if (firstSet[ch - \'a\'] == 0) {\n return false;\n }\n secondSet[ch - \'a\']++;\n }\n \n // Step 4: Check if the set of characters is the same\n for (int i = 0; i < 26; i++) {\n if (firstSet[i] == 0 && secondSet[i] > 0) {\n return false;\n }\n if (secondSet[i] == 0 && firstSet[i] > 0) {\n return false;\n }\n }\n \n // Step 5: Sort arrays\n sort(firstSet.begin(), firstSet.end());\n sort(secondSet.begin(), secondSet.end());\n \n // Step 6: Compare sorted arrays\n for (int i = 0; i < 26; i++) {\n if (firstSet[i] != secondSet[i]) {\n return false;\n }\n }\n \n // Step 7: If all checks pass, return true\n return true;\n }\n};\n```\n```C# []\npublic class Solution {\n public bool CloseStrings(string word1, string word2) {\n int l1 = word1.Length, l2 = word2.Length;\n if (l1 != l2) return false;\n if (word1.Equals(word2)) return true;\n\n int[] firstSet = new int[26];\n int[] secondSet = new int[26];\n \n for (int i = 0; i < l1; i++) {\n firstSet[word1[i] - \'a\']++;\n }\n \n for (int i = 0; i < l2; i++) {\n if (firstSet[word2[i] - \'a\'] == 0) return false;\n secondSet[word2[i] - \'a\']++;\n }\n \n Array.Sort(firstSet);\n Array.Sort(secondSet);\n\n for (int i = 25; i >= 0 && firstSet[i] != 0; i--) {\n if (firstSet[i] != secondSet[i]) {\n return false;\n }\n }\n \n return true;\n }\n}\n```\n```Python []\nclass Solution(object):\n def closeStrings(self, word1, word2):\n """\n :type word1: str\n :type word2: str\n :rtype: bool\n """\n l1, l2 = len(word1), len(word2)\n\n # Check if lengths are equal\n if l1 != l2:\n return False\n\n # Check if strings are already equal\n if word1 == word2:\n return True\n\n # Count occurrences of characters in word1\n first_set = [0] * 26\n for ch in word1:\n first_set[ord(ch) - ord(\'a\')] += 1\n\n # Count occurrences of characters in word2 and check for non-existing characters\n second_set = [0] * 26\n for ch in word2:\n if first_set[ord(ch) - ord(\'a\')] == 0:\n return False\n second_set[ord(ch) - ord(\'a\')] += 1\n\n # Sort the arrays to compare frequencies\n first_set.sort()\n second_set.sort()\n\n # Compare sorted arrays element by element\n for i in range(26):\n if first_set[i] != second_set[i]:\n return False\n\n return True\n```\n```Python3 []\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n # Step 1: Check if lengths are equal\n if len(word1) != len(word2):\n return False\n\n # Step 2: Check if strings are already equal\n if word1 == word2:\n return True\n\n # Step 3: Count occurrences of each character\n first_set = [0] * 26\n second_set = [0] * 26\n \n for ch in word1:\n first_set[ord(ch) - ord(\'a\')] += 1\n\n for ch in word2:\n if first_set[ord(ch) - ord(\'a\')] == 0:\n return False\n second_set[ord(ch) - ord(\'a\')] += 1\n\n # Step 4: Check if sets of characters are the same\n if set(first_set) != set(second_set):\n return False\n\n # Step 5: Sort both arrays\n first_set.sort()\n second_set.sort()\n\n # Step 6: Compare sorted arrays element by element\n for i in range(26):\n if first_set[i] != second_set[i]:\n return False\n\n # Step 7: If all conditions are satisfied, return True\n return True\n```\n```Javascript []\n/**\n * @param {string} word1\n * @param {string} word2\n * @return {boolean}\n */\nvar closeStrings = function(word1, word2) {\n // Step 1: Check if lengths are equal\n if (word1.length !== word2.length) {\n return false;\n }\n\n // Step 2: Check if the strings are already equal\n if (word1 === word2) {\n return true;\n }\n\n // Step 3: Count occurrences of each character\n const firstSet = new Array(26).fill(0);\n const secondSet = new Array(26).fill(0);\n\n for (let i = 0; i < word1.length; i++) {\n firstSet[word1.charCodeAt(i) - \'a\'.charCodeAt(0)]++;\n secondSet[word2.charCodeAt(i) - \'a\'.charCodeAt(0)]++;\n }\n\n // Step 4: Check if the set of characters is the same\n for (let i = 0; i < 26; i++) {\n if ((firstSet[i] === 0 && secondSet[i] !== 0) || (firstSet[i] !== 0 && secondSet[i] === 0)) {\n return false;\n }\n }\n\n // Step 5: Sort both arrays\n firstSet.sort((a, b) => a - b);\n secondSet.sort((a, b) => a - b);\n\n // Step 6: Compare the sorted arrays\n for (let i = 0; i < 26; i++) {\n if (firstSet[i] !== secondSet[i]) {\n return false;\n }\n }\n\n // Step 7: If all checks pass, return true\n return true;\n};\n```\n```Typescript []\nfunction closeStrings(word1: string, word2: string): boolean {\n const l1 = word1.length;\n const l2 = word2.length;\n\n if (l1 !== l2) return false;\n\n if (word1 === word2) return true;\n\n const firstSet: number[] = new Array(26).fill(0);\n const secondSet: number[] = new Array(26).fill(0);\n\n for (let i = 0; i < l1; i++) {\n const ch1 = word1.charCodeAt(i) - \'a\'.charCodeAt(0);\n firstSet[ch1]++;\n }\n\n for (let i = 0; i < l2; i++) {\n const ch2 = word2.charCodeAt(i) - \'a\'.charCodeAt(0);\n\n if (firstSet[ch2] === 0) return false;\n\n secondSet[ch2]++;\n }\n\n firstSet.sort((a, b) => a - b);\n secondSet.sort((a, b) => a - b);\n\n for (let i = 0; i < 26; i++) {\n if (firstSet[i] !== secondSet[i]) {\n return false;\n }\n }\n\n return true;\n}\n```\n# Upvote - PLEASE\n\n | 5 | 0 | ['Hash Table', 'String', 'C', 'Python', 'C++', 'Java', 'TypeScript', 'Python3', 'JavaScript', 'C#'] | 1 |
determine-if-two-strings-are-close | Python - O(NLogN) Solution with explanation | python-onlogn-solution-with-explanation-7hc57 | \n# Complexity\n- Time complexity: 0(nlogn) - for sorting the lists\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1) - we\'re storing con | sameeneeti | NORMAL | 2024-01-14T09:17:27.603389+00:00 | 2024-01-14T09:17:27.603431+00:00 | 746 | false | \n# Complexity\n- Time complexity: $$0(nlogn)$$ - for sorting the lists\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$ - we\'re storing constant chars\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n # if the words are of uneven length then they\'re not close\n if len(word1) != len(word2):\n return False\n\n # now we store the frequencies of each word\n freq1: List[int] = [0] * 26\n freq2: List[int] = [0] * 26\n\n for idx in range(len(word1)):\n char1 = ord(word1[idx]) - ord("a")\n char2 = ord(word2[idx]) - ord("a")\n\n freq1[char1] += 1\n freq2[char2] += 1\n\n # now two characters are close if their frequencies are some\n # e.g word1="abc", word2="bca", here the frequencies are same so once\n # we sort the lists and compare then we\'ll have our answer but consider\n # word1="abc", word2="xyz", here the frequencies are same as well but\n # the characters are not same, so first we make sure that the characters\n # are same, if any character is different then the words are not close\n # then we can compare their frequncies\n\n for idx in range(len(freq1)):\n # a character exists if it\'s frequency is greater than 0, so if a\n # character exists in word1 and doesn\'t in word2 then they\'re not close\n if freq1[idx] > 0 and freq2[idx] == 0:\n return False\n\n if freq2[idx] > 0 and freq1[idx] == 0:\n return False\n\n # now we sort the frequncies and if they\'re same they\'re close else not\n freq1.sort()\n freq2.sort()\n\n return freq1 == freq2\n\n``` | 5 | 0 | ['Python3'] | 0 |
determine-if-two-strings-are-close | C++ 🚀🚀UNIQUE APPROACH 😂😂🔥🔥🔥👌👌👌 C++ || MUST SEE 😍 | c-unique-approach-c-must-see-by-devilbac-nzk2 | Intuition & Approach :\nHope u all doing good. as i always come up with unique approaches so here i also came up with unique approach.. that i dont think anyone | DEvilBackInGame | NORMAL | 2024-01-14T07:48:27.453689+00:00 | 2024-01-14T07:51:43.826479+00:00 | 389 | false | # Intuition & Approach :\nHope u all doing good. as i always come up with unique approaches so here i also came up with unique approach.. that i dont think anyone came across.\n\nLets see the approach:\n1. i am assuming you have read the question, so i tried this question with some unique wayas eventually it worked \uD83D\uDE02\uD83D\uDD25.\n2. first i am checking if both string are equal length. thats a must part.\n3. then i am pushing both string in map `mp1` and `mp2` respectively.\n4. then again check if all element are same. means chars in `word1` should also be in `word2`.\nfor that i used `find()` in `mp1` finding element in `mp2`.\n5. then i also have to check that `frequency` of element should match with other , so in interchanging it will be easier.\n6. so i created `2 vector to save frequency` of both `word1 and word2` string taken from `mp1 and mp2` respectively .\n7. then i am sorting both `v1 `and `v2` `vectors` to easy for compare the `frequency/element`. if `frequency/elements` matches in both` v1 and v2 `vector `return true , else false`.\n\nSEE CODE BELOW FOR BETTER CLEARIFYING THE APPROACH :-\n# Code\n```C++ []\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n if(word1.size()!=word2.size()) return false;\n map<char,int>mp1;\n map<char,int>mp2;\n\n for(auto i:word1) mp1[i]++;\n for(auto i:word2) mp2[i]++;\n\n for(auto i:mp1){\n if(mp2.find(i.first)==mp2.end()) return false;\n }\n\n vector<int>v1;\n vector<int>v2;\n for(auto it:mp1){\n v1.push_back(it.second);\n }\n\n for(auto it:mp2){\n v2.push_back(it.second);\n }\n sort(v1.begin(),v1.end());\n sort(v2.begin(),v2.end());\n \n return v1==v2;\n }\n};\n```\n **DON\'T FORGET TO UPVOTE \u2B06.... Your appreciation fuels my enthusiasm to keep sharing solutions. \uD83D\uDE80 \uD83D\uDE0A\u26C4\u2744 \u2764** | 5 | 0 | ['Ordered Map', 'C++'] | 1 |
determine-if-two-strings-are-close | Easy to Understand | Set | HashMap | easy-to-understand-set-hashmap-by-ronitt-49l4 | Intuition\n Describe your first thoughts on how to solve this problem. \nNumber of Alphabet in Both Strings\n\n# Approach\n Describe your approach to solving th | RonitTomar | NORMAL | 2024-01-14T06:52:21.938525+00:00 | 2024-01-14T06:52:21.938555+00:00 | 841 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNumber of Alphabet in Both Strings\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStep 1 - if length is different Retuen false\nStep 2 - Using Set to Remove Duplicate\nStep 3 - Using HashMap To count Number of Alphabet\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\no(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\no(n)\n\n# Code\n```\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n int n = word1.length();\n int m = word2.length();\n System.out.println(n);\n System.out.println(m);\n\n if(n!=m){\n return false;\n }\n if(word1.equals(word2)) return true;\n \n Set<Character> hs1 = new HashSet<>();\n Set<Character> hs2 = new HashSet<>();\n\n for(int i=0;i<n;i++)\n {\n hs1.add(word1.charAt(i));\n }\n\n for(int i=0;i<m;i++)\n {\n hs2.add(word2.charAt(i));\n }\n\n if(hs1.size()!=hs2.size())\n {\n return false;\n }\n\n System.out.println(hs1);\n System.out.println(hs2);\n\n char ch1[] = new char[hs1.size()];\n char ch2[] = new char[hs2.size()];\n\n int k=0;\n for (Character element : hs1) {\n ch1[k]=element;\n System.out.print(element);\n k++;\n }\n System.out.println();\n \n int l=0;\n for (Character element : hs2) {\n ch2[l]=element;\n System.out.print(element);\n l++;\n }\n System.out.println();\n\n Arrays.sort(ch1);\n Arrays.sort(ch2);\n\n for(int i=0;i<ch1.length;i++)\n {\n if(ch1[i]!=ch2[i])\n {\n return false;\n }\n }\n\n HashMap<Character,Integer> hs3 = new HashMap<>();\n HashMap<Character,Integer> hs4 = new HashMap<>();\n\n for(int i=0;i<n;i++)\n {\n if(hs3.containsKey(word1.charAt(i)))\n {\n hs3.put(word1.charAt(i),hs3.get(word1.charAt(i))+1);\n }\n else{\n hs3.put(word1.charAt(i),1);\n }\n }\n\n System.out.println(hs3);\n\n for(int i=0;i<m;i++)\n {\n if(hs4.containsKey(word2.charAt(i)))\n {\n hs4.put(word2.charAt(i),hs4.get(word2.charAt(i))+1);\n }\n else{\n hs4.put(word2.charAt(i),1);\n }\n }\n\n System.out.println(hs4);\n\n ArrayList<Integer> arr1 = new ArrayList<>();\n ArrayList<Integer> arr2 = new ArrayList<>();\n\n for(Character key: hs3.keySet())\n {\n int value = hs3.get(key);\n arr1.add(value);\n }\n for(Character key: hs4.keySet())\n {\n int value = hs4.get(key);\n arr2.add(value);\n }\n\n Collections.sort(arr1);\n Collections.sort(arr2);\n\n for(int i=0;i<arr1.size();i++)\n {\n int temp = arr1.get(i);\n System.out.print(temp+" ");\n }\n System.out.println();\n\n for(int i=0;i<arr2.size();i++)\n {\n int temp = arr2.get(i);\n System.out.print(temp+" ");\n }\n\n\n int p = arr1.size();\n int o = arr2.size();\n\n // System.out.println(p);\n // System.out.println(o);\n\n if(p!=o)\n {\n return false;\n }\n\n for(int i=0;i<o;i++)\n {\n int temp1 = arr1.get(i);\n int temp2 = arr2.get(i);\n if(temp1!=temp2)\n {\n // System.out.println(arr1.get(i));\n // System.out.println(arr2.get(i));\n return false;\n }\n }\n\n return true;\n }\n}\n``` | 5 | 0 | ['Hash Table', 'String', 'Ordered Set', 'Java'] | 4 |
determine-if-two-strings-are-close | ✅Beats 69.52% Users || Java || Beginner Friendly Solution || EXPLAINED🔥 | beats-6952-users-java-beginner-friendly-ed0uj | \n\n\n# Approach\n Describe your approach to solving the problem. \n1. Return false if, the length of both the words are not equal.\n2. Frequency Counting:\n | soniraghav21 | NORMAL | 2024-01-14T05:29:32.118193+00:00 | 2024-01-14T05:29:32.118215+00:00 | 439 | false | \n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Return `false` if, the length of both the words are not `equal`.\n2. Frequency Counting:\n * Two arrays (`freq1` and `freq2`) are used to count the frequency of each letter in `word1` and `word2`.\n * `freq1[i]` stores the count of the i-th letter in the English alphabet in `word1`, and similarly for `freq2`.\n3. Checking Presence of Characters:\n * Iterate over each character in the alphabet.\n * If a character is present in one word and not in the other (or vice versa), return `false`.\n * This ensures that both words contain the same set of characters.\n4. Sorting Frequencies:\n * Sort the frequency arrays (`freq1` and `freq2`).\n * This step is necessary because the order of frequencies doesn\'t matter, only their values.\n5. Comparing Sorted Frequencies:\n * Iterate through the sorted frequency arrays and compare corresponding elements.\n * If any corresponding elements are not equal, return `false`.\n6. Final Result:\n * If all the checks pass, return `true`, indicating that the two words are "close" as per the problem definition.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n if(word1.length() != word2.length()){\n return false;\n }\n\n int[] freq1 = new int[26];\n int[] freq2 = new int[26];\n\n for(int i=0; i<word2.length(); i++){\n freq1[word1.charAt(i) - \'a\'] += 1;\n freq2[word2.charAt(i) - \'a\'] += 1;\n }\n\n for(int i=0; i<26; i++){\n if((freq1[i] != 0 && freq2[i] == 0) || (freq1[i] != 0 && freq2[i] == 0)){\n return false;\n }\n }\n\n Arrays.sort(freq1);\n Arrays.sort(freq2);\n\n for(int i=0; i<26; i++){\n if(freq1[i] != freq2[i]){\n return false;\n }\n }\n\n return true;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
determine-if-two-strings-are-close | ✅ Beats 100% | count frequencies and sort 😉 | beats-100-count-frequencies-and-sort-by-w0ruz | \n# Intuition\n Describe your first thoughts on how to solve this problem. \n The order does not matter, since we can swap easily.\n So we need to check if both | abdelazizSalah | NORMAL | 2024-01-14T04:48:57.654161+00:00 | 2024-01-14T04:49:32.859214+00:00 | 431 | false | \n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* The order does not matter, since we can swap easily.\n* So we need to check if both have the same set of characters.\n* and if so, we need to check that the order of frequencies are the same.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. if they have two different length, then for sure they are not close, so return false. \n\n## Count frequencies\n2. create a vector frequency for each word.\n3. iterate over each character in each word\n 1. increment the frequency of that character.\n4. iterate over all the alphabet\n 1. if one character exist in one word, and not in the other\n 1. return false. \n\n## sort the frequencies and compare.\n> Since we need to replace all the frequencies of certain character, so we care only that the frequency of that character is same as the other character we need to convert to in the other word\n\n* ie: aaabbc -> zzzddf, they are close since the frequencies vector will be 3, 2, 1 for both of them\n* but is such case abbbbc -> zzzddf, here we can not say that they are close, since we have frequency list {3,2,1} and the other is {4,1,1}.\n* so here what we should do.\n5. sort both freqencies vectors.\n6. iterate over the alphabet length \n 1. if the corresponding frequencies are not the same\n 1. return false.\n7. return true. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n1. O((26 Log (26)))-> which is constant O(1). \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n1. O(26)-> which is constant O(1). \n\n# Code\n```\n#pragma GCC optimize("O3")\n#pragma GCC optimize("Ofast", "inline", "ffast-math", "unroll-loops", "no-stack-protector")\n#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native", "f16c")\nstatic const auto DPSolver = []()\n{ std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return \'c\'; }();\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2)\n{\n DPSolver;\n if(word1.length() != word2.length())\n return false; \n vector<int> freq1(26); \n vector<int> freq2(26);\n for (char c : word1)\n freq1[c - \'a\'] ++;\n \n for (char c : word2)\n freq2[c - \'a\'] ++;\n \n for (int i = 0; i <26; i++)\n if (freq1[i] && !freq2[i])\n return false; \n else if (freq2[i] && !freq1[i])\n return false; \n\n sort(freq1.begin(), freq1.end(), greater<int>()); \n sort(freq2.begin(), freq2.end(), greater<int>()); \n for (int i = 0; i < 26; i++)\n if (freq1[i] != freq2[i])\n return false;\n \n\n return true;\n}\n};\n``` | 5 | 0 | ['Hash Table', 'String', 'Sorting', 'Counting', 'C++'] | 0 |
determine-if-two-strings-are-close | Beats 74.34%of users with Python3 | beats-7434of-users-with-python3-by-hashi-sg6p | \n\n# Approach\n- The approach taken in the code is to use the Counter class from the collections module to count the frequency of characters in both input stri | hashir-irfan | NORMAL | 2023-12-11T15:21:01.912288+00:00 | 2023-12-11T15:21:01.912322+00:00 | 519 | false | \n\n# Approach\n- The approach taken in the code is to use the Counter class from the collections module to count the frequency of characters in both input strings.\n- The code first checks if the lengths of the two strings are different, and if so, returns False because strings of different lengths cannot be close.\n- Then, it compares the sets of keys (characters) in both frequency dictionaries. If they are not the same, the strings cannot be close, so it returns False.\n- Next, the code sorts the dictionaries based on the frequency of characters.\n- Finally, it checks if the lists of frequencies in both dictionaries are the same. \n- If they are, the strings are close, and the function returns True; otherwise, it returns False.\n\n# Code\n```\nfrom collections import Counter\n\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n if len(word1) != len(word2):\n return False\n frequency1 = Counter(word1)\n frequency2 = Counter(word2)\n if set(frequency1.keys()) != set(frequency2.keys()):\n return False\n frequency1 = dict(sorted(frequency1.items(), key=lambda item: item[1]))\n frequency2 = dict(sorted(frequency2.items(), key=lambda item: item[1]))\n return [frequency for frequency in frequency1.values()] == [frequency for frequency in frequency2.values()]\n``` | 5 | 0 | ['Python3'] | 0 |
determine-if-two-strings-are-close | Three line, simple & fast solution | three-line-simple-fast-solution-by-yohan-t23v | Intuition\nTwo strings are close if they share the same characters and character frequencies, regardless of order.\n \n\n# Approach\n- Character Set Comparison | yohannesmelese4 | NORMAL | 2023-11-24T10:14:28.776215+00:00 | 2023-11-24T10:14:28.776236+00:00 | 543 | false | # Intuition\nTwo strings are close if they share the same characters and character frequencies, regardless of order.\n \n\n# Approach\n- **Character Set Comparison**: Ensure both strings contain identical characters.\n- **Frequency Comparison**: Check if the character frequencies match across both strings.\n\n# Complexity\n- Time complexity: $$O(n log(n\n))$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nfrom collections import Counter\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n a = Counter(word1)\n b = Counter(word2)\n\n return sorted(a.keys()) == sorted(b.keys()) and sorted(a.values()) == sorted(b.values())\n``` | 5 | 0 | ['Python3'] | 1 |
determine-if-two-strings-are-close | [rust] super concise O(N) | rust-super-concise-on-by-dolpm-mfgb | \nuse std::collections::HashMap;\nimpl Solution {\n pub fn close_strings(word1: String, word2: String) -> bool {\n // create mappings from characters | dolpm | NORMAL | 2022-12-02T10:56:25.498178+00:00 | 2022-12-02T10:56:25.498207+00:00 | 181 | false | ```\nuse std::collections::HashMap;\nimpl Solution {\n pub fn close_strings(word1: String, word2: String) -> bool {\n // create mappings from characters to their\n // frequencies in word1 and word2\n let (mut map1, mut map2) = ([0; 26], [0; 26]);\n for c in word1.chars() { map1[c as usize - 0x61] += 1; };\n for c in word2.chars() { map2[c as usize - 0x61] += 1; };\n \n // if there is character that one word contains\n // but the other doesn\'t, then they can\'t be \'close\'\n for i in 0..26 {\n if (map1[i] == 0 && map2[i] != 0) || (map1[i] != 0 && map2[i] == 0) {\n return false;\n }\n }\n \n // sort the maps such that we can make sure the amount of characters\n // with a given frequency match\n\t\t//\n\t\t// since maps are of size 26, this would be 2*O(26log26) === O(1)\n map1.sort();\n map2.sort();\n \n map1 == map2\n }\n}\n``` | 5 | 0 | ['Sorting', 'Rust'] | 0 |
determine-if-two-strings-are-close | ✅C++|| 99% faster || counting || commented soln. | c-99-faster-counting-commented-soln-by-y-rocn | \n\n\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n if(word1.length() != word2.length()) return false;\n int co | yuvraj0157 | NORMAL | 2022-12-02T05:16:32.084524+00:00 | 2023-01-03T07:31:27.538892+00:00 | 396 | false | \n\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n if(word1.length() != word2.length()) return false;\n int count1[26] = {0};\n int count2[26] = {0};\n for(int i = 0;i<word1.length();i++) //counting freq of word1 chars\n {\n count1[word1[i]-\'a\']++;\n }\n \n for(int i = 0;i<word2.length();i++) //counting freq of word2 chars\n {\n count2[word2[i]-\'a\']++;\n }\n \n for(int i = 0;i<26;i++) //checking if atleast 1 same chars are present in both string\n {\n if(count1[i] && count2[i] == 0) return false;\n }\n \n sort(count1,count1+26);\n sort(count2,count2+26);\n \n for(int i = 0;i<26;i++) //checking whether the frequencies present in word1 matches with word2, no matter which char freq it is\n {\n if(count1[i] != count2[i]) return false;\n }\n return true;\n }\n};\n```\nPls Upvote\n\uD83D\uDC4D\uD83D\uDE43 | 5 | 0 | ['Sorting', 'Counting', 'C++'] | 0 |
determine-if-two-strings-are-close | O(n) solution | on-solution-by-namanxk-unee | \nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n count1 = Counter(word1)\n count2 = Counter(word2)\n\n retu | namanxk | NORMAL | 2022-12-02T01:27:31.698492+00:00 | 2022-12-02T10:03:44.568512+00:00 | 846 | false | ```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n count1 = Counter(word1)\n count2 = Counter(word2)\n\n return set(count1.keys()) == set(count2.keys()) and Counter(count1.values()) == Counter(count2.values())\n``` | 5 | 1 | ['Python', 'Python3'] | 1 |
determine-if-two-strings-are-close | Detailed Java O(n) solution | Bit Manipulation Explained | detailed-java-on-solution-bit-manipulati-7t6x | The part where we have to count the frequency of characters is simple.\n\nThe real problem was finding a way to check if a given frequency in the frequency arr | mrprince88 | NORMAL | 2021-01-23T04:58:06.659545+00:00 | 2021-01-23T05:24:40.333435+00:00 | 324 | false | The part where we have to count the frequency of characters is simple.\n\nThe real problem was finding a way to check if a given frequency in the frequency array of second string occurs anywhere in the frequency array of the first string. HashSets can be used for that but where is the fun in that.\n\nTo solve this problem I used xor operation. Now, the xor gives 1 only if number of 1s in the input are 1. So if the xor operation ever encounter a condition when the number of 1s is odd, it will stay 1 until it is cancelled out in future by another same number.\n\nSuppose you encounter a frequency 5 in frequency array 1, it can only be cancelled out by another frequency 5 only. You can take 2 separate variables to calculate xor of all the frequencies in two strings separately and perform an xor of both the variables at last. But this will be same as having a single variable.\n\nA base case is if frequency of a character is zero in one string but not in another, then of course answer is false.\n\nPlease do not forget to upvote.\n\nHere is my solution: \n\n```\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n \n if(word1.length()!=word2.length())\n return false;\n \n int []d1=new int[26];\n int []d2=new int[26];\n \n\t\t// getting freq of each character\n for(int i=0;i<word1.length();i++) {\n char c=word1.charAt(i);\n d1[c-\'a\']++;\n }\n \n for(int i=0;i<word2.length();i++) {\n char c=word2.charAt(i);\n d2[c-\'a\']++;\n }\n \n int res=0;\n \n\t\t// performing xor operation\n for(int i=0;i<26;i++) {\n if((d1[i]==0 && d2[i]!=0) || (d2[i]==0 && d1[i]!=0))\n return false;\n res^=d1[i];\n res^=d2[i];\n }\n return res==0;\n }\n}\n``` | 5 | 0 | ['Bit Manipulation', 'Java'] | 1 |
determine-if-two-strings-are-close | Simple C++ Solution | simple-c-solution-by-pragumodi-4cjs | \nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n if(word1.size() != word2.size()) return false;\n vector<int> f1 | pragumodi | NORMAL | 2020-11-27T06:26:24.982971+00:00 | 2020-11-27T06:26:24.983014+00:00 | 240 | false | ```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n if(word1.size() != word2.size()) return false;\n vector<int> f1(26, 0), f2(26, 0);\n for(auto &c : word1) f1[c - \'a\']++;\n for(auto &c : word2) f2[c - \'a\']++;\n for(int i = 0; i < 26; i++) if(f1[i] > 0 != f2[i] > 0) return false;\n sort(f1.begin(), f1.end());\n sort(f2.begin(), f2.end()); \n for(int i = 0; i < 26; i++) if(f1[i] != f2[i]) return false;\n return true;\n }\n};\n``` | 5 | 0 | [] | 0 |
determine-if-two-strings-are-close | Elegant Kotlin solution using groupBy | elegant-kotlin-solution-using-groupby-by-o8bk | Code\n\nclass Solution {\n private fun String.getFrequencyList(): List<Int> {\n return groupBy { it }.map { it.value.size }.sorted()\n }\n\n fun | gaojude | NORMAL | 2024-01-14T19:55:11.840170+00:00 | 2024-01-14T19:55:11.840191+00:00 | 61 | false | # Code\n```\nclass Solution {\n private fun String.getFrequencyList(): List<Int> {\n return groupBy { it }.map { it.value.size }.sorted()\n }\n\n fun closeStrings(word1: String, word2: String): Boolean {\n return when {\n word1.length != word2.length -> false\n word1.toSet() != word2.toSet() -> false\n word1.getFrequencyList() != word2.getFrequencyList() -> false\n else -> true\n }\n }\n}\n``` | 4 | 0 | ['Kotlin'] | 0 |
determine-if-two-strings-are-close | 🚀🚀🚀 NO SORTiNG && NO HASHTABLE -> TC -> 🔥 O(N) 🔥 FRiENDLY EXPLAINED ✅ 🚀🚀🚀 | no-sorting-no-hashtable-tc-on-friendly-e-ctag | Intuition\nThe code appears to be solving a problem related to comparing two strings, word1 and word2, for certain properties. The goal seems to be determining | prodonik | NORMAL | 2024-01-14T19:05:26.441303+00:00 | 2024-01-14T19:26:01.673432+00:00 | 651 | false | # Intuition\nThe code appears to be solving a problem related to comparing two strings, `word1` and `word2`, for certain properties. The goal seems to be determining if the two words can be made equivalent by performing specific operations on them.\n\n# Approach\nThe solution defines a class named `Solution` with a method `closeStrings` that takes two strings as input and returns a boolean indicating whether the two strings can be made equivalent. The main steps in the approach are as follows:\n1. Check if the lengths of the two words are equal. If not, return false.\n2. Initialize arrays to store character frequencies (`chars1` and `chars2`) and cumulative character frequencies (`values1` and `values2`).\n3. Use the `process` method to update the character and cumulative frequency arrays for both words.\n4. Compare the character frequencies and cumulative frequencies to determine if the two words can be made equivalent.\n\n# Complexity\n- Time complexity: $$O(n)$$, where n is the length of the input words.\n- Space complexity: $$O(n)$$, as additional arrays are created to store character frequencies and cumulative frequencies.\n\n# Code Explanation\n```java []\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n // Check if the lengths are equal\n int length = word1.length();\n if (length != word2.length()) return false;\n\n // Initialize arrays for character frequencies and cumulative frequencies\n int [] chars1 = new int [26], chars2 = new int [26];\n int [] values1 = new int [length + 1], values2 = new int [length + 1];\n\n // Process word1 and word2 to update the frequency arrays\n process(chars1, values1, word1);\n process(chars2, values2, word2);\n\n // Check if characters present in word1 are also present in word2\n for (int i = 0; i < chars1.length; i++) {\n if (chars1[i] > 0 && chars2[i] == 0) return false;\n }\n\n // Check if cumulative frequencies are equal for both words\n for (int i = 0; i < length; i++) {\n if (values1[i] != values2[i]) return false;\n }\n\n // If all checks pass, the words can be made equivalent\n return true;\n }\n\n // Helper method to update character and cumulative frequencies\n private void process(int[] chars, int[] values, String word) {\n for (int i = 0; i < word.length(); i++) {\n chars[word.charAt(i) - \'a\']++;\n values[chars[word.charAt(i) - \'a\']]++;\n }\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n bool closeStrings(std::string word1, std::string word2) {\n // Check if the lengths are equal\n int length = word1.length();\n if (length != word2.length()) return false;\n\n // Initialize arrays for character frequencies and cumulative frequencies\n std::vector<int> chars1(26, 0), chars2(26, 0);\n std::vector<int> values1(length + 1, 0), values2(length + 1, 0);\n\n // Process word1 and word2 to update the frequency arrays\n process(chars1, values1, word1);\n process(chars2, values2, word2);\n\n // Check if characters present in word1 are also present in word2\n for (int i = 0; i < chars1.size(); i++) {\n if (chars1[i] > 0 && chars2[i] == 0) return false;\n }\n\n // Check if cumulative frequencies are equal for both words\n for (int i = 0; i < length; i++) {\n if (values1[i] != values2[i]) return false;\n }\n\n // If all checks pass, the words can be made equivalent\n return true;\n }\n\nprivate:\n // Helper method to update character and cumulative frequencies\n void process(std::vector<int>& chars, std::vector<int>& values, const std::string& word) {\n for (char c : word) {\n chars[c - \'a\']++;\n values[chars[c - \'a\']]++;\n }\n }\n};\n```\n```Python []\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n # Check if the lengths are equal\n length = len(word1)\n if length != len(word2):\n return False\n\n # Initialize arrays for character frequencies and cumulative frequencies\n chars1 = [0] * 26\n chars2 = [0] * 26\n values1 = [0] * (length + 1)\n values2 = [0] * (length + 1)\n\n # Process word1 and word2 to update the frequency arrays\n self.process(chars1, values1, word1)\n self.process(chars2, values2, word2)\n\n # Check if characters present in word1 are also present in word2\n for i in range(26):\n if chars1[i] > 0 and chars2[i] == 0:\n return False\n\n # Check if cumulative frequencies are equal for both words\n for i in range(length):\n if values1[i] != values2[i]:\n return False\n\n # If all checks pass, the words can be made equivalent\n return True\n\n # Helper method to update character and cumulative frequencies\n def process(self, chars, values, word):\n for c in word:\n chars[ord(c) - ord(\'a\')] += 1\n values[chars[ord(c) - ord(\'a\')]] += 1\n\n```\n```C# []\npublic class Solution {\n public bool CloseStrings(string word1, string word2) {\n // Check if the lengths are equal\n int length = word1.Length;\n if (length != word2.Length) return false;\n\n // Initialize arrays for character frequencies and cumulative frequencies\n int[] chars1 = new int[26];\n int[] chars2 = new int[26];\n int[] values1 = new int[length + 1];\n int[] values2 = new int[length + 1];\n\n // Process word1 and word2 to update the frequency arrays\n Process(chars1, values1, word1);\n Process(chars2, values2, word2);\n\n // Check if characters present in word1 are also present in word2\n for (int i = 0; i < 26; i++) {\n if (chars1[i] > 0 && chars2[i] == 0) return false;\n }\n\n // Check if cumulative frequencies are equal for both words\n for (int i = 0; i < length; i++) {\n if (values1[i] != values2[i]) return false;\n }\n\n // If all checks pass, the words can be made equivalent\n return true;\n }\n\n // Helper method to update character and cumulative frequencies\n private void Process(int[] chars, int[] values, string word) {\n foreach (char c in word) {\n chars[c - \'a\']++;\n values[chars[c - \'a\']]++;\n }\n }\n}\n\n```\n```Go []\npackage main\n\nimport "fmt"\n\ntype Solution struct{}\n\nfunc (s *Solution) CloseStrings(word1 string, word2 string) bool {\n\t// Check if the lengths are equal\n\tlength := len(word1)\n\tif length != len(word2) {\n\t\treturn false\n\t}\n\n\t// Initialize arrays for character frequencies and cumulative frequencies\n\tchars1 := make([]int, 26)\n\tchars2 := make([]int, 26)\n\tvalues1 := make([]int, length+1)\n\tvalues2 := make([]int, length+1)\n\n\t// Process word1 and word2 to update the frequency arrays\n\ts.process(chars1, values1, word1)\n\ts.process(chars2, values2, word2)\n\n\t// Check if characters present in word1 are also present in word2\n\tfor i := 0; i < 26; i++ {\n\t\tif chars1[i] > 0 && chars2[i] == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Check if cumulative frequencies are equal for both words\n\tfor i := 0; i < length; i++ {\n\t\tif values1[i] != values2[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// If all checks pass, the words can be made equivalent\n\treturn true\n}\n\n// Helper method to update character and cumulative frequencies\nfunc (s *Solution) process(chars []int, values []int, word string) {\n\tfor _, c := range word {\n\t\tchars[c-\'a\']++\n\t\tvalues[chars[c-\'a\']]++\n\t}\n}\n\n```\n```JavaScript []\nclass Solution {\n closeStrings(word1, word2) {\n // Check if the lengths are equal\n const length = word1.length;\n if (length !== word2.length) return false;\n\n // Initialize arrays for character frequencies and cumulative frequencies\n const chars1 = new Array(26).fill(0);\n const chars2 = new Array(26).fill(0);\n const values1 = new Array(length + 1).fill(0);\n const values2 = new Array(length + 1).fill(0);\n\n // Process word1 and word2 to update the frequency arrays\n this.process(chars1, values1, word1);\n this.process(chars2, values2, word2);\n\n // Check if characters present in word1 are also present in word2\n for (let i = 0; i < 26; i++) {\n if (chars1[i] > 0 && chars2[i] === 0) return false;\n }\n\n // Check if cumulative frequencies are equal for both words\n for (let i = 0; i < length; i++) {\n if (values1[i] !== values2[i]) return false;\n }\n\n // If all checks pass, the words can be made equivalent\n return true;\n }\n\n // Helper method to update character and cumulative frequencies\n process(chars, values, word) {\n for (const c of word) {\n chars[c.charCodeAt(0) - \'a\'.charCodeAt(0)]++;\n values[chars[c.charCodeAt(0) - \'a\'.charCodeAt(0)]]++;\n }\n }\n}\n\n```\n```Ruby []\nclass Solution\n def close_strings(word1, word2)\n # Check if the lengths are equal\n length = word1.length\n return false if length != word2.length\n\n # Initialize arrays for character frequencies and cumulative frequencies\n chars1 = Array.new(26, 0)\n chars2 = Array.new(26, 0)\n values1 = Array.new(length + 1, 0)\n values2 = Array.new(length + 1, 0)\n\n # Process word1 and word2 to update the frequency arrays\n process(chars1, values1, word1)\n process(chars2, values2, word2)\n\n # Check if characters present in word1 are also present in word2\n (0..25).each do |i|\n return false if chars1[i] > 0 && chars2[i] == 0\n end\n\n # Check if cumulative frequencies are equal for both words\n (0..length - 1).each do |i|\n return false if values1[i] != values2[i]\n end\n\n # If all checks pass, the words can be made equivalent\n true\n end\n\n private\n\n # Helper method to update character and cumulative frequencies\n def process(chars, values, word)\n word.each_char do |c|\n chars[c.ord - \'a\'.ord] += 1\n values[chars[c.ord - \'a\'.ord]] += 1\n end\n end\nend\n```\n | 4 | 0 | ['C', 'C++', 'Java', 'Go', 'Python3', 'Ruby', 'JavaScript', 'C#'] | 4 |
determine-if-two-strings-are-close | ✅ EASY C++ SOLUTION ☑️ | easy-c-solution-by-2005115-4mz6 | PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT\n# CONNECT WITH ME\n### https://www.linkedin.com/in/pratay-nandy-9ba57b229/\n#### https://www.instagram.com/pratay_nand | 2005115 | NORMAL | 2024-01-14T13:17:25.276370+00:00 | 2024-01-14T13:17:25.276410+00:00 | 119 | false | # **PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT**\n# **CONNECT WITH ME**\n### **[https://www.linkedin.com/in/pratay-nandy-9ba57b229/]()**\n#### **[https://www.instagram.com/pratay_nandy/]()**\n\n# Approach\n### Explanation\n1. **Function Signature:**\n - `bool closeStrings(string s1, string s2)`: This function takes two strings, `s1` and `s2`, and determines whether they are "close" strings.\n\n2. **Size Check:**\n - `if (s1.size() != s2.size()) return false;`: Checks if the lengths of the two strings are different. If they are not of equal length, the function returns `false` because strings of different lengths cannot be considered "close."\n\n3. **Frequency and Presence Vectors:**\n - `vector<int> freqw1(26, 0), freqw2(26, 0);`: Initializes vectors to store the frequency of each character in the alphabet for both `s1` and `s2`.\n - `vector<int> countw1(26, 0), countw2(26, 0);`: Initializes vectors to store whether each character in the alphabet is present in both `s1` and `s2`.\n\n4. **Frequency and Presence Calculation:**\n - Two loops iterate through each character in `s1` and `s2`.\n - For each character, the frequency count is incremented, and the presence is marked in the corresponding vectors.\n\n5. **Sorting Frequency Vectors:**\n - `sort(freqw1.begin(), freqw1.end());` and `sort(freqw2.begin(), freqw2.end());`: Sorts the frequency vectors to prepare them for comparison.\n\n6. **Comparison and Return:**\n - `if (freqw1 == freqw2 && countw1 == countw2) return true;`: Checks if the sorted frequency vectors and presence vectors are equal. If they are, the function returns `true`, indicating that the strings are "close." Otherwise, it returns `false`.\n\nThis code appears to be checking whether two strings are "close" based on the criteria of having the same character frequencies and the same set of characters (presence of each character) in both strings.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:**0(N)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:**0(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n# Code\n```\nclass Solution {\npublic:\n bool closeStrings(string s1, string s2) {\n if(s1.size()!= s2.size())return false;\n vector<int>freqw1(26,0),freqw2(26,0);\n vector<int>countw1(26,0),countw2(26,0);\n for(char c : s1)\n {\n freqw1[c-\'a\']++;\n countw1[c-\'a\'] = 1 ;\n }\n for(char c : s2)\n {\n freqw2[c-\'a\']++;\n countw2[c-\'a\'] = 1 ;\n }\n sort(freqw2.begin(),freqw2.end());\n sort(freqw1.begin(),freqw1.end());\n if(freqw1 == freqw2 &&countw1 == countw2 )return true;\n else{\n return false;\n }\n }\n};\n``` | 4 | 0 | ['String', 'Sorting', 'Counting', 'C++'] | 0 |
determine-if-two-strings-are-close | Beats 94% Of Solutions Easy Solution Using Hash Table 🔥🔥 🚀 | beats-94-of-solutions-easy-solution-usin-jjr0 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\nInitialize Frequency Arrays:\n\nTwo arrays, temp1 and temp2, of size 26 | BabaTillu | NORMAL | 2024-01-14T13:10:20.443435+00:00 | 2024-01-14T13:10:20.443470+00:00 | 476 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\nInitialize Frequency Arrays:\n\nTwo arrays, temp1 and temp2, of size 26 are initialized to store the frequency of each character in the alphabet (assuming the strings only contain lowercase English letters).\nCount Character Frequencies:\n\nTwo for loops iterate through each character in word1 and word2, respectively. In each iteration, the corresponding index in the temp1 and temp2 arrays is incremented based on the character\'s position in the alphabet.\nCheck for Same Characters:\n\nThe code then checks if the two strings have the same set of characters. It does so by iterating through the temp1 array and checking if, for each character position, either both strings have that character (both frequencies are greater than 0) or both strings do not have that character (both frequencies are equal to 0). If this condition is not met for any character position, the function returns false, indicating that the two strings are not close.\nSort Frequency Arrays:\n\nThe frequency arrays (temp1 and temp2) are then sorted using the sort function. This is done to compare the frequency distributions of characters in the next step.\nCheck Frequency Distributions:\n\nThe code compares each element of the sorted temp1 and temp2 arrays. If any corresponding elements are not equal, the flag variable is set to false, indicating that the frequency distributions are not the same.\nFinal Result:\n\nThe function returns flag, which is true if the two strings are close (i.e., they have the same set of characters and the same frequency distribution), and false otherwise.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: o(n);\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(n);\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n bool closeStrings(string word1, string word2) {\n\n vector<int>temp1(26);\n vector<int>temp2(26);\n bool flag = true;\n\n for(int i = 0; i < word1.size();i++){\n temp1[word1[i]-\'a\']++;\n }\n\n for(int i = 0; i < word2.size();i++){\n temp2[word2[i]-\'a\']++;\n }\n\n for(int i = 0; i < temp1.size();i++){\n if((temp1[i]>0 && temp2[i]==0) || (temp1[i]==0 && temp2[i]>0)){\n return false;\n }\n }\n\n sort(temp1.begin(),temp1.end());\n sort(temp2.begin(),temp2.end());\n\n for(int i = 0;i < 26;i++){\n if(temp1[i]!=temp2[i]){\n flag = false;\n break;\n }\n }\n\n return flag;\n \n }\n};\n``` | 4 | 0 | ['Hash Table', 'C++'] | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.