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
maximum-product-of-the-length-of-two-palindromic-subsequences
C++ EASY RECURSION + BACKTRACKING
c-easy-recursion-backtracking-by-the_exp-yrzx
```\nclass Solution {\npublic:\n int ans =-1;\n bool ispal(vector&a)\n {\n int n=a.size();\n for(int i=0;i&s1,vector\&s2,int i)\n {\n
the_expandable
NORMAL
2022-02-28T09:07:24.662365+00:00
2022-02-28T09:07:24.662396+00:00
139
false
```\nclass Solution {\npublic:\n int ans =-1;\n bool ispal(vector<char>&a)\n {\n int n=a.size();\n for(int i=0;i<n/2;i++)\n {\n if(a[i] != a[n-1-i])return false;\n }\n return true;\n }\n void solve(string s,vector<char>&s1,vector<char>&s2,int i)\n {\n // base case \n if(i >= s.size())\n {\n if(ispal(s1) && ispal(s2))\n {\n int p = (s1.size()*s2.size());\n if(ans < p)ans=p;\n return ;\n }\n else\n return ;\n }\n solve(s,s1,s2,i+1);\n \n s1.push_back(s[i]);\n solve(s,s1,s2,i+1);\n s1.pop_back();\n \n s2.push_back(s[i]);\n solve(s,s1,s2,i+1);\n s2.pop_back();\n }\n int maxProduct(string s) {\n vector<char>s1,s2 ; \n solve(s,s1,s2,0);\n return ans;\n }\n};
1
0
['Backtracking']
0
maximum-product-of-the-length-of-two-palindromic-subsequences
C++ || BITMASK
c-bitmask-by-easy_coder-cm2d
```\nclass Solution {\npublic:\n \n bool isPalindrome(string s){\n if(s.size() == 1) return true;\n string tmp = s;\n reverse(tmp.beg
Easy_coder
NORMAL
2022-01-18T07:33:20.924362+00:00
2022-01-18T07:33:20.924394+00:00
269
false
```\nclass Solution {\npublic:\n \n bool isPalindrome(string s){\n if(s.size() == 1) return true;\n string tmp = s;\n reverse(tmp.begin(),tmp.end());\n return tmp == s;\n }\n \n int maxProduct(string s) {\n int n = s.size();\n map<int,int> mp;\n for(int mask=1; mask < (1<<n); mask++){\n string subseq;\n for(int i=0; i<n; i++){\n if((mask & 1<<i))\n subseq += s[i];\n }\n \n if(isPalindrome(subseq)){\n mp[mask] = subseq.size();\n }\n }\n \n int ans = INT_MIN;\n \n for(auto it1 = mp.begin(); it1 != mp.end(); it1++){\n for(auto it2 = mp.begin(); it2 != mp.end(); it2++){\n if( (it1->first & it2->first) == 0){\n ans = max(ans, it1->second * it2->second);\n }\n }\n }\n \n return ans;\n \n }\n};
1
0
['Bit Manipulation', 'C', 'Bitmask']
1
maximum-product-of-the-length-of-two-palindromic-subsequences
Maximum Product of the Length of Two Palindromic Subsequences | C++ | LPS
maximum-product-of-the-length-of-two-pal-kgnp
LPS : Longest Palindromic Subsequence\n\nclass Solution {\npublic:\n int LPS(string& s1) {\n string s2 = s1;\n reverse(s2.begin(), s2.end());\n
renu_apk
NORMAL
2022-01-15T18:15:00.133151+00:00
2022-01-15T18:15:28.271072+00:00
216
false
LPS : Longest Palindromic Subsequence\n```\nclass Solution {\npublic:\n int LPS(string& s1) {\n string s2 = s1;\n reverse(s2.begin(), s2.end());\n \n int n = s1.size();\n int dp[n + 1][n + 1];\n for(int i = 0; i < n; i++) dp[i][0] = 0, dp[0][i] = 0;\n \n for(int i = 1; i <= n; i++){\n for(int j = 1; j <= n; j++){\n if(s1[i - 1] == s2[j - 1]){\n dp[i][j] = 1 + dp[i - 1][j - 1];\n }\n else dp[i][j] = max(dp[i - 1][j],dp[i][j - 1]);\n }\n }\n return dp[n][n];\n }\n\n int maxProduct(string s) {\n int ans = 0, n = s.size();\n for(int mask = 1; mask < (1 << n) - 1; mask++){\n string a = "", b = "";\n for(int i = 0; i < n; i++){\n if(mask & (1 << i)) a += s[i];\n else b += s[i];\n }\n ans = max(ans, LPS(a) * LPS(b));\n }\n return ans;\n }\n};\n```
1
0
[]
1
maximum-product-of-the-length-of-two-palindromic-subsequences
faster than 93.69%, less than 94.86% , C++, simple and concise
faster-than-9369-less-than-9486-c-simple-rqko
\nclass Solution {\npublic:\n int maxProduct(string s) {\n int n=s.size();\n int maskMax=1<<n-1;\n \n int ret=0;\n for(int
zzwolf1306489
NORMAL
2022-01-11T08:38:43.071031+00:00
2022-01-11T08:38:43.071074+00:00
132
false
```\nclass Solution {\npublic:\n int maxProduct(string s) {\n int n=s.size();\n int maskMax=1<<n-1;\n \n int ret=0;\n for(int mask=1;mask<maskMax;mask++){\n string s1,s2;\n for(int i=0;i<s.size();i++){\n if(mask & 1<<i)\n s1+=s[i];\n else\n s2+=s[i];\n }\n int MaxLen1=helper(s1, 0, s1.size()-1);\n int MaxLen2=helper(s2, 0, s2.size()-1);\n ret=max(ret, MaxLen1*MaxLen2);\n }\n \n return ret;\n }\n \n int helper(string& s, int l, int r){\n if(l>r)\n return 0;\n if(l==r)\n return 1;\n if(s[l]==s[r])\n return 2+helper(s, l+1, r-1);\n else\n return max(helper(s, l+1, r), helper(s, l, r-1));\n }\n};\n```
1
0
[]
0
maximum-product-of-the-length-of-two-palindromic-subsequences
Java | Simple | Backtracking
java-simple-backtracking-by-pagalpanda-9xpp
\npublic int maxProduct(String s) {\n solve(s, "", "", 0);\n return ans;\n }\n int ans;\n void solve(String s, String s1, String s2, int
pagalpanda
NORMAL
2021-09-28T01:48:43.278101+00:00
2021-09-28T01:48:43.278132+00:00
370
false
```\npublic int maxProduct(String s) {\n solve(s, "", "", 0);\n return ans;\n }\n int ans;\n void solve(String s, String s1, String s2, int start) {\n if(start == s.length()) {\n if(isPal(s1) && isPal(s2)) {\n int val = s1.length()*s2.length();\n ans = Math.max(ans, val);\n }\n return;\n }\n char ch = s.charAt(start);\n solve(s, s1+ch, s2, start+1);\n solve(s, s1, s2+ch, start+1);\n solve(s, s1, s2, start+1);\n }\n \n boolean isPal(String s) {\n int i = 0;\n int j = s.length() -1;\n while(i<j) {\n if(s.charAt(i) != s.charAt(j)) {\n return false;\n }\n i++;\n j--;\n }\n return true;\n }\n```
1
0
['Backtracking', 'Java']
0
maximum-product-of-the-length-of-two-palindromic-subsequences
C++ creating all subsets and storing them
c-creating-all-subsets-and-storing-them-93o97
\nclass Solution {\npublic:\n bool isPalindrome(string str){\n int i=0,j = str.length()-1;\n while(i<j){\n if(str[i]!=str[j])return
shvmkj
NORMAL
2021-09-18T10:51:01.937979+00:00
2021-09-18T10:51:01.938013+00:00
149
false
```\nclass Solution {\npublic:\n bool isPalindrome(string str){\n int i=0,j = str.length()-1;\n while(i<j){\n if(str[i]!=str[j])return false;\n i++;\n j--;\n }\n return true;\n }\n int maxProduct(string s) {\n int n = s.length();\n vector<int>pal;\n for(int i=1;i<((1<<n)-1);i++){\n string str = "";\n for(int j=0;j<n;j++){\n if((1<<j)&i){\n str+=s[j];\n }\n }\n if(isPalindrome(str)){\n pal.push_back(i);\n }\n }\n int ans = INT_MIN;\n int n2 = pal.size();\n for(int i = 0;i<n2-1;i++){\n for(int j = i+1;j<n2;j++){\n if(((pal[i]&pal[j])==0)){\n int a = __builtin_popcount(pal[i]);\n int b = __builtin_popcount(pal[j]);\n ans = max(ans,a*b);}\n }\n }\n return ans;\n }\n};\n```
1
0
[]
0
maximum-product-of-the-length-of-two-palindromic-subsequences
Disjoint subsequence | Bitmasking | dp | c++
disjoint-subsequence-bitmasking-dp-c-by-3m3fl
\nint max_palindrome(string a)\n {\n int n = a.size();\n if(n==0)\n return 0;\n vector<vector<int>> dp(n, vector<int>(n,0));
Dr_Strange_10
NORMAL
2021-09-15T10:25:40.590135+00:00
2021-09-15T10:25:40.590167+00:00
308
false
```\nint max_palindrome(string a)\n {\n int n = a.size();\n if(n==0)\n return 0;\n vector<vector<int>> dp(n, vector<int>(n,0));\n for(int i=0;i<n;i++)\n {\n dp[i][i] = 1;\n }\n\t\t\n\t\t// dist is the distance between i and j pointer...\n for(int dist = 1; dist < n;dist++)\n {\n for(int i = 0; i<n-1;i++)\n {\n\t\t\t\t// j = i +dist...\n\t\t\t\t// if j >= n, j is pointing to any valid char in string... So break...\n if(i+dist>=n)\n break;\n else\n {\n int j = i+dist;\n if(a[i]==a[j])\n dp[i][j] = dp[i+1][j-1]+2;\n else\n dp[i][j] = max(dp[i][j-1],dp[i+1][j]);\n }\n }\n }\n return dp[0][n-1];\n }\n int maxProduct(string s) {\n int n = s.length();\n\t\t\n\t\t// say if s = "abcd", mask = 1111, where each 1 corresponds to char at that place\n\t\t// So mask = 1011 corresponds to string "acd", neglecting \'b\' as its bit is turned off.\n\t\t\n int mask = pow(2,n)-1;\n long long max = 0;\n string final_a,final_b;\n for(int i = 0;i<=mask;i++)\n {\n string a="",b="";\n\t\t\t\n\t\t\t// i is mask for string a..\n\t\t\t// mask2 is for string b..\n\t\t\t\n\t\t\t// mask2 = mask^i will turn in those bits for those characters which are not in a..\n\t\t\t// like say a = "abd" then i = 1101, then mask2 will become 1111^1101 = 0010 --> c\n\t\t\t\n int mask2 = mask^i;\n\t\t\t\n\t\t\t// constructing a...\n for(int j=0;j<n;j++)\n {\n if(1<<j & i)\n a += s[j];\n }\n\t\t\t//constructing b\n for(int j=0;j<n;j++)\n {\n if(1<<j & mask2)\n b += s[j];\n }\n\t\t\t\n\t\t\t//finding max palidrome for each subsequence...\n long long max_a = max_palindrome(a), max_b = max_palindrome(b);\n\t\t\t\n\t\t\t\n if(max_a*max_b > max )\n {\n max = max_a*max_b;\n }\n }\n return max;\n }\n```
1
0
['Dynamic Programming', 'Bitmask']
1
maximum-product-of-the-length-of-two-palindromic-subsequences
recursion and bitset
recursion-and-bitset-by-michelusa-ehxd
This approach:\n identify all palindroms\n store found palindroms as a bitset of their character positions in an unordered set\n* enumerate all combinations to
michelusa
NORMAL
2021-09-14T15:15:32.516917+00:00
2021-09-14T15:22:26.369930+00:00
53
false
This approach:\n* identify all palindroms\n* store found palindroms as a bitset of their character positions in an unordered set\n* enumerate all combinations to find the max product (length is how many bits are set)\n\n\nExplaining a bit the recursion: we can either have a character or not in the sequence we are building\n\n\n```\n\n string input;\n bool is_pal(const string& str) const {\n if (str.empty())\n return false;\n if (str.size() == 1)\n return true;\n for (size_t pos = 0; pos != str.size() / 2; ++pos) { \n if (str[pos] != str[str.size() - pos - 1])\n return false; \n }\n return true;\n }\n \n unordered_set<bitset<12>> all_pals;\n \n void find_all_pals(const string& str, bitset<12> poses, const size_t pos) {\n \n if (is_pal(str)) {\n \n all_pals.insert(poses);\n }\n \n if (pos == input.size() )\n return ;\n \n find_all_pals(str, poses, pos + 1); \n poses.set(pos);\n find_all_pals(str + input[pos], poses, pos + 1);\n \n \n }\npublic:\n int maxProduct(string s) {\n \n input = s;\n \n find_all_pals("", {}, 0);\n \n \n int count {0};\n for (const auto& first : all_pals) {\n for (const auto& second : all_pals) { \n if ((first & second).none()) {\n count = max<int>(count, first.count() * second.count());\n }\n }\n }\n \n \n \n return count;\n }
1
0
['C']
0
maximum-product-of-the-length-of-two-palindromic-subsequences
(C++) 2002. Maximum Product of the Length of Two Palindromic Subsequences
c-2002-maximum-product-of-the-length-of-7l36g
\n\nclass Solution {\npublic:\n int maxProduct(string s) {\n int n = s.size(); \n vector<int> dp(1 << n); \n for (int mask = 1; mask < (
qeetcode
NORMAL
2021-09-13T17:58:55.476889+00:00
2021-09-13T18:09:13.031701+00:00
113
false
\n```\nclass Solution {\npublic:\n int maxProduct(string s) {\n int n = s.size(); \n vector<int> dp(1 << n); \n for (int mask = 1; mask < (1 << n); ++mask) \n if ((mask & mask-1) == 0) dp[mask] = 1; \n else {\n int lo = log2(mask & ~(mask-1)), hi = log2(mask); \n if (s[lo] == s[hi]) dp[mask] = 2 + dp[mask^(1<<lo)^(1<<hi)]; \n else dp[mask] = max(dp[mask^(1<<lo)], dp[mask^(1<<hi)]);\n }\n \n int ans = 0; \n for (int mask = 0; mask < (1 << n); ++mask) {\n int comp = (1 << n) - 1 ^ mask; \n ans = max(ans, dp[mask] * dp[comp]); \n }\n return ans; \n }\n};\n```
1
0
['C']
0
maximum-product-of-the-length-of-two-palindromic-subsequences
[Python3] bitmask dp
python3-bitmask-dp-by-ye15-oqf9
Please check out this commit for solutions of weekly 258. \n\nclass Solution:\n def maxProduct(self, s: str) -> int:\n \n @cache\n def l
ye15
NORMAL
2021-09-13T14:59:14.593590+00:00
2021-09-13T18:13:32.527286+00:00
187
false
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/0de189059bd6af4dabe23d9066dde1655f3334fc) for solutions of weekly 258. \n```\nclass Solution:\n def maxProduct(self, s: str) -> int:\n \n @cache\n def lps(mask): \n """Return length of longest palindromic sequence."""\n if not mask: return 0\n if not mask & (mask-1): return 1\n lo = int(log2(mask & ~(mask-1))) # least significant set bit\n hi = int(log2(mask)) # most significant set bit \n if s[lo] == s[hi]: return 2 + lps(mask^(1<<lo)^(1<<hi))\n return max(lps(mask^(1<<lo)), lps(mask^(1<<hi)))\n \n ans = 0\n for mask in range(1 << len(s)): \n comp = (1 << len(s)) - 1 ^ mask\n ans = max(ans, lps(mask) * lps(comp))\n return ans \n```
1
0
['Python3']
0
maximum-product-of-the-length-of-two-palindromic-subsequences
NOT 2^n. O(n^2) + O(p^2) where n is length of string and p is number of palindromes
not-2n-on2-op2-where-n-is-length-of-stri-8tup
\n/*\n\tO(n^2) + O(plogp) where p is number of palindromes\n\n\tAlgorithm: for each posible palindrome starting charactera look at each possible palindrome end
justacoder3
NORMAL
2021-09-12T18:14:54.819966+00:00
2021-09-12T20:21:10.539866+00:00
66
false
```\n/*\n\tO(n^2) + O(plogp) where p is number of palindromes\n\n\tAlgorithm: for each posible palindrome starting charactera look at each possible palindrome end character, and if valid, add it\'s length and mask of bits, set corresponding to which positions were used by the palindrome, to a list of palindromes \n\n\tThen sort the list from longest to shortest palindrome and check to see which two, lengths multiplied together, are the maximum value.\n\n*/\nvar maxProduct = function(s) {\n let seen = [];\n function dfs(lo, hi, len, used) {\n for (let i = lo; i < hi; ++i) {\n for (let j = hi; j >= i; --j) {\n if (s[i] === s[j]) {\n if (i === j) {\n if (len > 0) {\n seen.push([len + 1, used | (1 << i)]);\n }\n } else if (i === j - 1) {\n seen.push([len + 2, used | (1 << i) | (1 << j)]);\n } else if (i === j - 2) {\n seen.push([len + 3, used | (1 << i) | (1 << j) | (1 << (i + 1))]); \n seen.push([len + 2, used | (1 << i) | (1 << j)]); \n } else {\n seen.push([len + 2, used | (1 << i) | (1 << j)]); \n dfs(i + 1, j - 1, len + 2, used | (1 << i) | (1 << j));\n }\n } else if (len > 0) {\n seen.push([len + 1, used | (1 << j)]);\n }\n }\n }\n }\n for (let i = 0; i < s.length; ++i) {\n seen.push([1, 1 << i]);\n }\n dfs(0, s.length - 1, 0, 0);\n seen.sort( (a,b) => b[0] - a[0] );\n let ans = 1;\n for (let i = 0; i < seen.length; ++i) {\n for (let j = i + 1; j < seen.length; ++j) {\n if ((seen[i][1] & seen[j][1]) === 0) {\n let num = seen[i][0] * seen[j][0];\n if (num < ans) {\n break;\n }\n ans = num;\n }\n }\n }\n return ans;\n};\n\n```
1
0
[]
1
maximum-product-of-the-length-of-two-palindromic-subsequences
much faster than bitmask 100ms 100%
much-faster-than-bitmask-100ms-100-by-ak-8dtm
\nclass Solution:\n def maxProduct(self, s: str) -> int:\n \n @lru_cache(None)\n def findBigPalLen(x): #O(n^2)\n if len(x) <=
akbc
NORMAL
2021-09-12T13:59:04.155324+00:00
2021-09-12T14:00:57.177868+00:00
163
false
```\nclass Solution:\n def maxProduct(self, s: str) -> int:\n \n @lru_cache(None)\n def findBigPalLen(x): #O(n^2)\n if len(x) <= 1: return len(x)\n if x[0] == x[-1]: return 2 + findBigPalLen(x[1:-1])\n return max(findBigPalLen(x[1:]), findBigPalLen(x[:-1]))\n \n @lru_cache(None)\n def findAllPal(x): #Fast pruning\n if len(x) == 0: \n return [""], [x]\n \n Idx = defaultdict(list)\n for i,l in enumerate(x): \n Idx[l].append(i)\n \n X, Y = [""], [x]\n for i in range(len(x)):\n X.append(x[i])\n Y.append(x[:i] + x[i + 1:])\n for j in Idx[x[i]]:\n if j > i:\n X1, Y1 = findAllPal(x[i + 1 : j])\n for k in range(len(X1)):\n X.append(x[i] + X1[k] + x[j])\n Y.append(x[:i] + Y1[k] + x[j + 1:])\n return X,Y\n X, Y = findAllPal(s)\n return max(len(X[i]) * findBigPalLen(Y[i]) for i in range(len(X)))\n```
1
0
['Python3']
0
maximum-product-of-the-length-of-two-palindromic-subsequences
C++ bottom-up DP mask
c-bottom-up-dp-mask-by-walter01-m7nw
Let dp[mask] denotes the longest length of palindromic subsequence in the string "mask" specifies. For example, mask = "11010", s = "abcad", mask has the sequen
walter01
NORMAL
2021-09-12T08:57:24.144886+00:00
2021-09-12T08:57:24.144915+00:00
42
false
Let dp[mask] denotes the longest length of palindromic subsequence in the string "mask" specifies. For example, mask = "11010", s = "abcad", mask has the sequence of "a, b, a", and dp[mask] = 3; other code is exactly to find the longest length of palindromic. \n\n\n\'\'\'\n\n int maxProduct(string s) {\n\t\t\tint n = s.size();\n\t\t\tvector<int> dp(1<<n, 0);\n\t\t\t//calculated only one letter in the subsequence, it obviously equals to 1.\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tdp[1<<i] = 1;\n\t\t\t}\n\t\t\tfor (int mask = 1; mask < (1 << n); mask++) {\n\t\t\t\tint left = 0, right = 0;\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\tif (mask & (1 << i)) {\n\t\t\t\t\t\tleft = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (int i = n - 1; i >= 0; i--) {\n\t\t\t\t\tif (mask & (1 << i)) {\n\t\t\t\t\t\tright = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//we must make sure mask has at least two "1", since only one "1" is calculated.\n\t\t\t\tif (left == right) continue;\n\n\t\t\t\tint newmask = mask - (1<<left) - (1 << right);\n\t\t\t\tif (s[left] == s[right]) dp[mask] = dp[newmask] + 2;\n\t\t\t\telse {\n\t\t\t\t\tdp[mask] = max(dp[mask - (1<<left)], dp[mask - (1<<right)]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tint res = -1;\n\t\t\tint allones = (1<<n) - 1;\n\t\t\tfor (int mask = 1; mask < (1 << n); mask++) {\n\t\t\t\tres = max(res, dp[mask] * dp[allones - mask]);\n\t\t\t}\n\t\t\treturn res;\n }\n\n\n\'\'\'
1
0
[]
0
maximum-product-of-the-length-of-two-palindromic-subsequences
Python DFS + Memorisation
python-dfs-memorisation-by-jamescandy-kudx
Intuition: similar to LCS, we loop through every possible combination of parlimdromic subsequences, but also introduce two extra parameter, exclude which is the
jamescandy
NORMAL
2021-09-12T05:12:39.993494+00:00
2021-09-12T06:34:55.965147+00:00
261
false
Intuition: similar to LCS, we loop through every possible combination of parlimdromic subsequences, but also introduce two extra parameter, `exclude` which is the indexes of first palindromic subsequences, `num` indicating the number of palindromic subsequences e.g. 0 means first subsequence, 1 means second subsequence.\n\n\n```\nclass Solution:\n def maxProduct(self, s: str) -> int:\n n = len(s)\n @cache\n def dfs(i: int, j: int, exclude: Tuple[int], num: int) -> int:\n if i > j:\n\t\t\t\t# we found the first palindromic subsequence, go start find the second one, then return the product\n if num == 0:\n ret = dfs(0, n-1, exclude, 1)\n return ret * len(exclude)\n return 0\n if num == 1 and i in exclude:\n return dfs(i+1, j, exclude, num)\n if num == 1 and j in exclude:\n return dfs(i, j-1, exclude, num)\n if s[i] == s[j]:\n add = 1 if i == j else 2\n e2 = exclude\n if num == 0:\n if i == j:\n e2 = exclude + (i,)\n else:\n e2 = exclude + (i, j)\n\t\t\t\t\t# We only return the length of second subsequence, first subsequence length can be retrieved with len(exclude)\n add = 0\n r1 = dfs(i+1, j-1, e2, num) + add\n\t\t\t\t# putting (n, 0) so we can treat the current exclude as the first subsequence, force dfs to start find the second subsequence\n r2 = dfs(n, 0, e2, num)\n r3 = dfs(n, 0, exclude + (j,), num)\n r4 = dfs(n, 0, exclude + (i,), num)\n r5 = dfs(i+1, j-1, exclude, num)\n return max(r1, r2, r3, r4, r5)\n else:\n r1 = dfs(i+1, j, exclude, num)\n r2 = dfs(i, j-1, exclude, num)\n r3 = dfs(i+1, j-1, exclude, num)\n r4 = dfs(n, 0, exclude + (j,), num)\n r5 = dfs(n, 0, exclude + (i,), num)\n return max(r1, r2, r3, r4, r5)\n \n return dfs(0, n - 1, tuple(), 0)\n```
1
0
['Depth-First Search', 'Python']
0
maximum-product-of-the-length-of-two-palindromic-subsequences
Isn't this insane how a small change (pass by reference) allows TLE to become AC
isnt-this-insane-how-a-small-change-pass-k15p
Isn\'t this insane how this small change allows the same solution to pass? Shouldn\'t leetcode be able to discern this is not some major change and allow both?\
ritam777
NORMAL
2021-09-12T04:59:59.395449+00:00
2021-09-12T05:02:11.382068+00:00
128
false
Isn\'t this insane how this small change allows the same solution to pass? Shouldn\'t leetcode be able to discern this is not some major change and allow both?\n\nAccepted\n```\nclass Solution {\npublic:\n int res, n;\n string str;\n bool isPalin(string s, int n) {\n for (int i=0; i<n/2; i++) {\n if (s[i] != s[n-1-i]) return false;\n }\n return true;\n }\n int max(int a, int b) {\n if (a >= b) {\n return a;\n }\n return b;\n }\n int max(int a, int b, int c) {\n int m = max(a,b);\n return max(m,c);\n }\n int go(int idx, string &s1, string &s2) {\n if (idx == n) {\n int l1 = s1.size();\n int l2 = s2.size();\n if (isPalin(s1, l1) && isPalin(s2, l2)) {\n res = max(res, l1*l2);\n }\n return res;\n }\n string s3 = s1 + str[idx];\n string s4 = s2 + str[idx];\n return max(go(idx+1, s1, s2), go(idx+1, s3, s2), go(idx+1, s1, s4));\n }\n int maxProduct(string s) {\n n = s.size();\n res = 0;\n str = s;\n string s1 = "";\n string s2 = "";\n return max(go(0,s1,s2), res);\n }\n};\n```\n\nTLE:\n```\nclass Solution {\npublic:\n int res, n;\n string str;\n bool isPalin(string s, int n) {\n for (int i=0; i<n/2; i++) {\n if (s[i] != s[n-1-i]) return false;\n }\n return true;\n }\n int max(int a, int b) {\n if (a >= b) {\n return a;\n }\n return b;\n }\n int max(int a, int b, int c) {\n int m = max(a,b);\n return max(m,c);\n }\n int go(int idx, string s1, string s2) {\n if (idx == n) {\n int l1 = s1.size();\n int l2 = s2.size();\n if (isPalin(s1, l1) && isPalin(s2, l2)) {\n res = max(res, l1*l2);\n }\n return res;\n }\n return max(go(idx+1, s1, s2), go(idx+1, s1 + str[idx], s2), go(idx+1, s1, s2 + str[idx]));\n }\n int maxProduct(string s) {\n n = s.size();\n res = 0;\n str = s;\n return max(go(0,"",""), res);\n }\n};\n```
1
0
[]
0
maximum-product-of-the-length-of-two-palindromic-subsequences
C++ || Check All subsequences
c-check-all-subsequences-by-debo01-25pd
Check All subsequences\nand check their lps.\nthen finally return the max possible ans.\n\nclass Solution {\npublic:\n int ans=1;\n unordered_map<string,i
debo01
NORMAL
2021-09-12T04:47:14.669064+00:00
2021-09-12T04:52:32.264208+00:00
143
false
Check All subsequences\nand check their lps.\nthen finally return the max possible ans.\n```\nclass Solution {\npublic:\n int ans=1;\n unordered_map<string,int>um;\n void func(string s,string x,string y,int i){\n \n if(i==s.length()){\n ans=max(ans,functiontofindlps(x)*functiontofindlps(y));\n return ;\n }\n func(s,x+s[i],y,i+1);\n func(s,x,y+s[i],i+1);\n }\n int functiontofindlps(string s){\n int n=s.length();\n if(n==0)return 0;\n if(um.count(s))return um[s];\n vector<vector<int>>dp(n+1,vector<int>(n+1));\n string r=s;\n reverse(s.begin(),s.end());\n for(int i=1;i<=n;i++){\n for(int j=1;j<=n;j++){\n if(s[i-1]==r[j-1]){\n dp[i][j]=dp[i-1][j-1]+1;\n }else{\n dp[i][j]=max(dp[i-1][j],dp[i][j-1]);\n }\n }\n }\n return um[s]=dp[n][n];\n }\n int maxProduct(string s) {\n func(s,"","",0);\n return ans;\n }\n};\n```
1
0
['Backtracking', 'C']
1
maximum-product-of-the-length-of-two-palindromic-subsequences
javascript bitmask brute force 1239ms
javascript-bitmask-brute-force-1239ms-by-4si3
Main idea:\n(1) get all palindrome subsequence\n(2) parse all ways of picking two of them, if disjoint, max the product in result.\n\nconst isPalindrome = (s) =
henrychen222
NORMAL
2021-09-12T04:26:12.997897+00:00
2021-09-12T04:37:48.404352+00:00
316
false
Main idea:\n(1) get all palindrome subsequence\n(2) parse all ways of picking two of them, if disjoint, max the product in result.\n```\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\n\nconst maxProduct = (s) => {\n let a = [];\n let n = s.length;\n let N = 2 ** n; // equal to 1 << n \n for (let i = 0; i < N; i++) { // mask\n let sub = \'\';\n let idx = new Set();\n for (let j = 0; j < n; j++) {\n if (i & (1 << j)) {\n sub += s[j];\n idx.add(j);\n }\n }\n if (isPalindrome(sub)) { // save all palindrome subsequence with index Set\n a.push([sub, idx]);\n }\n }\n let an = a.length;\n let res = 0;\n for (let i = 0; i < an; i++) {\n for (let j = i + 1; j < an; j++) {\n if (isDisjoint(a[i][0], a[j][0], a[i][1], a[j][1])) {\n let len = a[i][0].length * a[j][0].length; // product\n res = Math.max(res, len);\n }\n }\n }\n return res;\n};\n\nconst isDisjoint = (s, t, is, it) => { // two subsequence index Set should be different, no same index\n for(const i of is) {\n if (it.has(i)) return false;\n }\n return true;\n};\n```
1
0
['Bitmask', 'JavaScript']
1
maximum-product-of-the-length-of-two-palindromic-subsequences
[python] iterative based brute force solution
python-iterative-based-brute-force-solut-w0ay
things to notice :\n1.deep copy\n2. covering every start point\n```\nclass Solution:\n def maxProduct(self, s: str) -> int:\n q= deque()\n for
user4436h
NORMAL
2021-09-12T04:13:20.698886+00:00
2021-09-12T04:45:35.706459+00:00
114
false
things to notice :\n1.deep copy\n2. covering every start point\n```\nclass Solution:\n def maxProduct(self, s: str) -> int:\n q= deque()\n for i in range(len(s)):\n q.append((s[i],[i]))\n ml=0\n n=0\n while q:\n st,li=q.pop()\n if st==st[::-1]:\n s2=\'\'\n for x in range(len(s)):\n if x not in li:\n s2+=s[x]\n if s2!=\'\':\n l1=len(st)\n q2=deque()\n for i in range(len(s2)):\n q2.append((s2[i],[i]))\n while q2:\n st2,li2=q2.pop()\n if st2==st2[::-1]:\n ml=max(l1*len(st2),ml)\n for j in range(li2[-1]+1,len(s2)):\n ls2=li2[:]\n ls2.append(j)\n q2.append((st2+s2[j],ls2))\n\n for i in range(li[-1]+1,len(s)):\n ls=li[:]\n ls.append(i)\n q.append((st+s[i],ls))\n return ml
1
0
['Iterator', 'Python']
0
maximum-product-of-the-length-of-two-palindromic-subsequences
Brute force: Bitmask + Longest Palindromic Subsequence
brute-force-bitmask-longest-palindromic-bw5yi
Generate all possible splits of s into two sequences of minimum 1 character (using bitmask).\nRun the longest palindromic subsequence algorithm on both parts an
prezes
NORMAL
2021-09-12T04:10:35.395984+00:00
2021-09-12T04:13:40.818403+00:00
163
false
Generate all possible splits of s into two sequences of minimum 1 character (using bitmask).\nRun the[ longest palindromic subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/) algorithm on both parts and return the max encountered product.\n\n```\nclass Solution {\n public int maxProduct(String s) {\n char[] ca= s.toCharArray();\n int n= ca.length, k= 1 << n, max= 1;\n char[] seq1= new char[12], seq2= new char[12];\n for(int i=1; i<k-1; i++){\n int n1= 0, n2= 0;\n for(int j= 0; j<n; ++j){\n if((i & (1<<j)) != 0) seq1[n1++]= ca[j];\n else seq2[n2++]= ca[j];\n }\n int lps1= lps(seq1, 0, n1-1), lps2= lps(seq2, 0, n2-1);\n max= Math.max(max, lps1*lps2);\n }\n return max;\n }\n\n int lps(char[] seq, int i, int j) {\n if(i==j) return 1;\n if(seq[i]==seq[j] && i+1 == j) return 2;\n if(seq[i]==seq[j]) return lps(seq, i+1, j-1) + 2;\n return Math.max(lps(seq, i, j-1), lps(seq, i+1, j));\n }\n}
1
0
['Bitmask']
0
maximum-product-of-the-length-of-two-palindromic-subsequences
Java | Backtracking
java-backtracking-by-ashish10comp-fzue
\n\nclass Solution {\n private int maxProduct;\n\n public int maxProduct(String s) {\n maxProduct = 0;\n populateMaxProduct(s, new StringBui
ashish10comp
NORMAL
2021-09-12T04:07:18.257353+00:00
2021-09-12T04:07:18.257392+00:00
164
false
```\n\nclass Solution {\n private int maxProduct;\n\n public int maxProduct(String s) {\n maxProduct = 0;\n populateMaxProduct(s, new StringBuilder(), new StringBuilder(), 0);\n return maxProduct;\n }\n\n private void populateMaxProduct(String s, StringBuilder s1, StringBuilder s2, int pos) {\n int length = s.length();\n if(pos == length) {\n if(isPalindrome(s1.toString()) && isPalindrome(s2.toString())) {\n maxProduct = Math.max(maxProduct, (s1.length() * s2.length()));\n }\n return;\n }\n char ch = s.charAt(pos);\n s1.append(ch);\n populateMaxProduct(s, s1, s2, (pos + 1));\n s1.deleteCharAt(s1.length() - 1);\n s2.append(ch);\n populateMaxProduct(s, s1, s2, (pos + 1));\n s2.deleteCharAt(s2.length() - 1);\n populateMaxProduct(s, s1, s2, (pos + 1));\n }\n\n private boolean isPalindrome(String s) {\n int low = 0, high = (s.length() - 1);\n while(low < high) {\n if(s.charAt(low) != s.charAt(high)) {\n return false;\n }\n low++;\n high--;\n }\n return true;\n }\n}\n\n```
1
0
[]
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++/Java Two Sum O(n * m)
cjava-two-sum-on-m-by-votrubac-hz2s
This looks very similar to Two Sum, and we will use Two Sum: Approach 3.\n\nWe just need to call our function "Two Product" :)\n\n> Update: see below for the op
votrubac
NORMAL
2020-09-06T04:00:32.959731+00:00
2020-09-06T19:26:29.343002+00:00
6,955
false
This looks very similar to Two Sum, and we will use [Two Sum: Approach 3](https://leetcode.com/problems/two-sum/solution/).\n\nWe just need to call our function "Two Product" :)\n\n> Update: see below for the optimized version!\n\n**C++**\n```cpp\nint numTriplets(vector<int>& n1, vector<int>& n2) {\n return accumulate(begin(n1), end(n1), 0, [&](int s, long n) { return s + twoProduct(n * n, n2); }) \n + accumulate(begin(n2), end(n2), 0, [&](int s, long n) { return s + twoProduct(n * n, n1); });\n}\nint twoProduct(long i, vector<int> &n) {\n unordered_map<int, int> m;\n int cnt = 0;\n for (auto v : n) {\n if (i % v == 0)\n cnt += m[i / v];\n ++m[v];\n }\n return cnt;\n} \n```\n\n**Java**\n```java\npublic int numTriplets(int[] n1, int[] n2) {\n long res = 0;\n for (long n : n1)\n res += twoProduct(n * n, n2);\n for (long n : n2)\n res += twoProduct(n * n, n1);\n return (int)res;\n}\nlong twoProduct(long i, int[] n) {\n Map<Long, Long> m = new HashMap<>();\n long cnt = 0;\n for (long v : n) {\n if (i % v == 0)\n cnt += m.getOrDefault(i / v, 0l);\n m.put(v, m.getOrDefault(v, 0l) + 1);\n }\n return cnt;\n} \n```\n\n#### Optimized Version\nWe can memoise the result for a given `n`. This will speed up things quite a bit if there is a lot of duplicates. We can use a hashmap, or we can sort the array so duplicates are next to each other. The solution below is an improvement from ~800 ms to ~280 ms.\n\n**C++**\n```cpp\nint numTriplets(vector<int>& n1, vector<int>& n2) {\n return countForArray(n1, n2) + countForArray(n2, n1);\n}\nint countForArray(vector<int>& n1, vector<int>& n2) {\n int res = 0, last_res = 0, last_n = 0;\n sort(begin(n1), end(n1));\n for (auto i = 0; i < n1.size(); last_n = n1[i++])\n if (n1[i] == last_n)\n res += last_res;\n else\n res += last_res = twoProduct((long)n1[i] * n1[i], n2);\n return res;\n}\nint twoProduct(long i, vector<int> &n) {\n unordered_map<int, int> m;\n int cnt = 0;\n for (auto v : n) {\n if (i % v == 0)\n cnt += m[i / v];\n ++m[v];\n }\n return cnt;\n} \n```
94
2
[]
9
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++ O(MN) with explanation
c-omn-with-explanation-by-lzl124631x-0gmq
See my latest update in repo LeetCode\n\n## Solution 1.\n\nType 1 and Type 2 are symmetrical so we can define a function count(A, B) which returns the count of
lzl124631x
NORMAL
2020-09-06T04:02:39.697855+00:00
2020-09-09T07:15:28.670931+00:00
3,369
false
See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1.\n\nType 1 and Type 2 are symmetrical so we can define a function `count(A, B)` which returns the count of the Type 1 triples. The answer is `count(A, B) + count(B, A)`.\n\nFor `count(A, B)`, we can use a `unordered_map<int, int> m` to store the frequency of the numbers in `B`. Then for each number `a` in `A`, the `target` value is `a * a`. We traverse the map `m` to count the triplets.\n\nFor each entry `(b, cnt)` in `m`:\n* If `target` is not divisible by `b` or `target / b` is not in `m`, there is no triplets, skip.\n* If `target / b == b`, we need to pick 2 out of `cnt` numbers so we can add `cnt * (cnt - 1)` triplets to the answer.\n* Otherwise, we can add `cnt * m[target / b]` triplets to the answer.\n\nSince we count the the pairs in `B` twice, we need to divide the answer by 2 before returning.\n\n```cpp\n// OJ: https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/\n// Author: github.com/lzl124631x\n// Time: O(N^2)\n// Space: O(N)\nclass Solution {\n int count(vector<int> &A, vector<int> &B) {\n int ans = 0;\n unordered_map<int, int> m;\n for (int n : B) m[n]++;\n for (int a : A) {\n long target = (long)a * a;\n for (auto &[b, cnt] : m) {\n if (target % b || m.count(target / b) == 0) continue;\n if (target / b == b) ans += cnt * (cnt - 1);\n else ans += cnt * m[target / b];\n }\n }\n return ans / 2;\n }\npublic:\n int numTriplets(vector<int>& A, vector<int>& B) {\n return count(A, B) + count(B, A);\n }\n};\n```
38
1
[]
7
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
python solution
python-solution-by-akaghosting-osfq
\tclass Solution:\n\t\tdef numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n\t\t\td1 = collections.defaultdict(int)\n\t\t\td2 = collections.defaul
akaghosting
NORMAL
2020-09-06T04:24:16.273455+00:00
2022-07-17T16:10:12.570724+00:00
1,718
false
\tclass Solution:\n\t\tdef numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n\t\t\td1 = collections.defaultdict(int)\n\t\t\td2 = collections.defaultdict(int)\n\t\t\tres = 0\n\t\t\tfor num1 in nums1:\n\t\t\t\td1[num1 * num1] += 1\n\t\t\tfor num2 in nums2:\n\t\t\t\td2[num2 * num2] += 1 \n\t\t\tfor i in range(len(nums1) - 1):\n\t\t\t\tfor j in range(i + 1, len(nums1)):\n\t\t\t\t\tres += d2[nums1[i] * nums1[j]]\n\t\t\tfor i in range(len(nums2) - 1):\n\t\t\t\tfor j in range(i + 1, len(nums2)):\n\t\t\t\t\tres += d1[nums2[i] * nums2[j]]\n\t\t\treturn res
19
0
[]
5
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Java Simple sort
java-simple-sort-by-hobiter-0q55
An easy way to sort and count:\n1, sort all arrays by non-decreasing order;\n2, for each i, shrink from left and right as j and k, then find each triples\n3, ha
hobiter
NORMAL
2020-09-06T04:02:10.027572+00:00
2020-09-13T20:39:55.335942+00:00
1,624
false
An easy way to sort and count:\n1, sort all arrays by non-decreasing order;\n2, for each i, shrink from left and right as j and k, then find each triples\n3, handle special case for dups, such as[1, 1], [1, 1, 1]\nTime: O(M*N)\nSpace: O(1)\n\n```\nclass Solution {\n public int numTriplets(int[] a, int[] b) {\n Arrays.sort(a);\n Arrays.sort(b);\n return cnt(a, b) + cnt(b, a);\n }\n \n private int cnt(int[] a, int[] b) {\n int res = 0, m = a.length, n = b.length;\n for (int i = 0; i < m; i++) {\n long t = ((long) a[i]) * ((long) a[i]);\n for (int l = 0, r = n - 1; l < n - 1; l++) { // finding pairs for i, l, r;\n if (((long) b[l]) * ((long) b[r]) < t) continue;\n while (r >= l && ((long) b[l]) * ((long) b[r]) > t) r--;\n if (r <= l) break;\n if (((long) b[l]) * ((long) b[r]) == t) {\n int orig = r;\n while(r > l && b[r] == b[orig]) { // [1, 1], [1, 1, 1]\n r--;\n res++;\n }\n r = orig; // reset to next cont;\n }\n }\n }\n return res;\n }\n}\n```\n\nThere is a better solution to use HashMap turn the l, r findings to O(n) 2-sum ones:\nThat is straightforward and easy understanding.\nAnother good point is that you don\'t have to sort the arrays.\nTime: O(M * N)\nspace: O(max(M, N));\n```\nclass Solution {\n public int numTriplets(int[] a, int[] b) {\n return cnt(a, b) + cnt(b, a);\n }\n \n private int cnt(int[] a, int[] b) {\n int res = 0, m = a.length;\n for (int i = 0; i < m; i++) {\n Map<Long, Integer> map = new HashMap<>();\n long t = ((long) a[i]) * ((long) a[i]);\n for (long n : b) { //must transferred to long\n if (t % n == 0) res += map.getOrDefault(t / n, 0); //new pair formed btw n and previous found t / n\n map.put(n, map.getOrDefault(n, 0) + 1); // cached the count found;\n }\n }\n return res;\n }\n}\n```\n\n
15
4
[]
4
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
c++ solution O(n*m) using hash_map
c-solution-onm-using-hash_map-by-dilipsu-8x3m
\n#define ll long long int\nclass Solution {\npublic:\n int find(vector<int>nums1,vector<int>nums2)\n {\n unordered_map<ll,ll>mp;\n for(int
dilipsuthar17
NORMAL
2021-03-01T11:23:02.867305+00:00
2021-03-01T11:23:02.867346+00:00
656
false
```\n#define ll long long int\nclass Solution {\npublic:\n int find(vector<int>nums1,vector<int>nums2)\n {\n unordered_map<ll,ll>mp;\n for(int i=0;i<nums2.size();i++)\n {\n for(int j=i+1;j<nums2.size();j++)\n {\n ll p=(long long)nums2[i]*nums2[j];\n mp[p]++;\n }\n }\n ll count=0;\n for(int i=0;i<nums1.size();i++)\n {\n ll p=(long long)nums1[i]*nums1[i];\n if(mp.find(p)!=mp.end())\n {\n count+=mp[p];\n }\n }\n return count;\n }\n int numTriplets(vector<int>& nums1, vector<int>& nums2) \n {\n return find(nums1,nums2)+find(nums2,nums1);\n }\n};\n```
11
0
[]
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Python | Instructions to code | Intuitive
python-instructions-to-code-intuitive-by-bsuj
\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n def is_perf_sqrt(n): \n """\n returns bo
prodcode
NORMAL
2020-09-06T04:05:32.412492+00:00
2020-09-06T04:18:47.924374+00:00
886
false
```\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n def is_perf_sqrt(n): \n """\n returns bool if a number is a perfect square\n like 4, 16, 25 --> True\n """\n return int(math.sqrt(n) + 0.5) ** 2 == n\n\n nums1_cntr, nums2_cntr = Counter(nums1), Counter(nums2)\n\n s = 0\n for x, y in itertools.combinations(nums2, 2):\n if is_perf_sqrt(x * y): \n\t\t\t\t# if product is perfect square, get count of sqrt(of_product)\n\t\t\t\ts += nums1_cntr[math.sqrt(x * y)]\n\t\t\n\t\t# similar vice-versa logic\n for x, y in itertools.combinations(nums1, 2):\n if is_perf_sqrt(x * y): s += nums2_cntr[math.sqrt(x * y)]\n\n return s\n```
11
0
[]
5
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Java solution using sorting. With explanation and comments. 4 ms. Faster than 100%.
java-solution-using-sorting-with-explana-aed1
Sort both arrays.\n2. Similar to the Two sum we have to find all the pairs that matches to the target. Target is the Square number. \n3. Start with left pointer
shaishavjogani
NORMAL
2020-09-06T05:05:43.505364+00:00
2020-09-08T06:20:11.271116+00:00
662
false
1. Sort both arrays.\n2. Similar to the Two sum we have to find all the pairs that matches to the target. Target is the Square number. \n3. Start with left pointer set to 0, and right pointer set to length-1.\n4. Must handle duplicates. \n\t* \te.g. Target: 4, nums = [1,1,4,4]\n\t* \tSo, total 4 pairs with indexes (0,2), (1,2), (0,3), (1,3)\n\t* \twhen left = 0, and right = 3, we found one pair. (0,3)\n\t\t* \tNow before updating left or right pointer, travesre through all values from left+1 to right whose value is same as nums[left]. It will give us the multiplication equals to target.\n\t\t* \tThis way we will find next pair (1,3).\n\t* Decrement right pointer, and reset left pointer.\n4. Repeat this process for all values in both arrays.\n\nRead the code comments for some added optimization.\n\n```\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n Arrays.sort(nums1);\n Arrays.sort(nums2);\n \n int count = 0;\n count += triplets(nums1, nums2);\n count += triplets(nums2, nums1);\n \n return count; \n }\n \n public int triplets(int[] nums1, int[] nums2) {\n \n\t\tMap<Long, Integer> seen = new HashMap<>();\n int count = 0;\n \n for(int i=0; i<nums1.length; i++) {\n long sqr = (long) nums1[i] * nums1[i]; //Target Value. Don\'t forget to convert to Long\n if(seen.containsKey(sqr)) { //If we have already seen the target value, then no need to repeat the process and find the pairs. \n count += seen.get(sqr);\n continue;\n }\n \n int localCount = 0; //Find the pairs for current Target\n int left = 0, right = nums2.length-1; \n\t\t\t\n while(left < right) { //Similar to Two sum, find all pairs whose multiplication equals to Target\n if(nums2[left] > sqr) // For optimization. If the lowest value is larger than target then break the loop.\n break;\n long multiple = (long) nums2[left] * nums2[right];\n \n if(sqr == multiple) {\n if(nums2[left] == nums2[right]) { //Special Case: when numbers from left to right are same. \n\t\t\t\t\t\tint n = right - left+1; // In the case the total pairs will be n*(n-1)/2.\n localCount += n * (n-1)/2;\n break;\n }\n localCount++; // Found one pair: Increament the counter.\n int newL = left+1; //To handle duplicates pairs, we will check all numbers from left side. Numbers must be same as the left number for equal multiplication.\n for(newL = left+1; newL < right && nums2[newL] == nums2[left]; newL++) {\n localCount++; \n }\n right--;\n \n } else if (multiple < sqr)\n left++;\n else\n right--;\n }\n\t\t\t\n\t\t\tcount += localCount;\n seen.put(sqr, localCount); //Add the pairs for target value in seen.\n\t\t\t\n }\n return count;\n }\n}\n```\n\n** Thanks to nanwu6805 for optimization suggestion. We do no need to repeat the same process and can use the count. I changed it a bit and instead used hashmap.
7
0
[]
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Python3 | Using Counter
python3-using-counter-by-tbvho-rsoo
For both nums1 and nums2, aggregate all the squares in nums1 and nums2. We will use this to easily track all occurences of nums1[i] * nums1[j] in nums2 and num
tbvho
NORMAL
2020-09-06T04:14:05.027809+00:00
2020-09-06T04:14:05.027871+00:00
429
false
For both nums1 and nums2, aggregate all the squares in nums1 and nums2. We will use this to easily track all occurences of nums1[i] * nums1[j] in nums2 and nums2[i] * nums2[j] in nums1. Then just use nested loops to generate possible combinations that could be in either frequency table.\n\n\n```\nimport collections\n\nclass Solution:\n \n # nums will be where nums[j] and nums[k] come from\n # Look for nums[j] * nums[k] in counts, if it exists grab count from frequency table "counts"\n def aggregateType(self, nums, counts):\n total = 0\n \n for i in range(0, len(nums)):\n for j in range(i + 1, len(nums)):\n target = nums[i] * nums[j]\n total += counts[target]\n \n return total\n \n def numTriplets(self, nums1, nums2):\n \n #Build frequency table of the squares you can form from num1 and num2\n counter1 = collections.Counter([num ** 2 for num in nums1])\n counter2 = collections.Counter([num ** 2 for num in nums2])\n \n return self.aggregateType(nums1, counter2) + self.aggregateType(nums2, counter1)\n```
7
0
[]
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++ | Two Pointer | 100 % faster
c-two-pointer-100-faster-by-csachdeva-50t0
\nclass Solution {\npublic:\n int countTriplet(vector<int>& nums1, vector<int>& nums2) {\n int count = 0, left, right;\n long num1Val, num2Val;
csachdeva
NORMAL
2020-09-06T04:37:44.518554+00:00
2020-09-06T09:03:42.497546+00:00
969
false
```\nclass Solution {\npublic:\n int countTriplet(vector<int>& nums1, vector<int>& nums2) {\n int count = 0, left, right;\n long num1Val, num2Val;\n unordered_map<int, int> freq;\n \n for(int i = 0; i < nums2.size(); i++) freq[nums2[i]]++;\n \n for(int i = 0; i < nums1.size(); i++) {\n left = 0;\n right = nums2.size()-1;\n num1Val = (long)nums1[i] * nums1[i];\n while(left < right) {\n num2Val = (long)nums2[left] * nums2[right];\n if(num1Val == num2Val) {\n if(nums2[right] == nums2[left]) {\n count += (freq[nums2[right]] * (freq[nums2[right]]-1))/2;\n break;\n }\n count += freq[nums2[right]] * freq[nums2[left]];\n left += freq[nums2[left]];\n right -= freq[nums2[right]];\n } else if(num1Val > num2Val) {\n left++;\n } else {\n right--;\n }\n }\n }\n return count;\n }\n \n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n sort(nums1.begin(), nums1.end());\n sort(nums2.begin(), nums2.end());\n return countTriplet(nums1, nums2) + countTriplet(nums2, nums1);\n }\n};\n```
6
0
[]
2
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Straightforward solution - brute force with optimized search using set
straightforward-solution-brute-force-wit-5pcz
\nclass Solution {\npublic:\n bool perfectSquare(long long int n) {\n long long int ans = sqrt(n);\n return n == ans*ans;\n }\n \n int
interviewrecipes
NORMAL
2020-09-06T04:04:04.484495+00:00
2020-09-06T04:04:04.484538+00:00
631
false
```\nclass Solution {\npublic:\n bool perfectSquare(long long int n) {\n long long int ans = sqrt(n);\n return n == ans*ans;\n }\n \n int squareRoot(long long int n) {\n int ans = sqrt(n);\n return ans;\n }\n \n int findTriplets(vector<int> a, vector<int> b) {\n int ans = 0;\n unordered_map<int, int> frequency;\n for (auto &y: b) {\n frequency[y]++;\n }\n int n = a.size();\n for (int i=0; i<n-1; i++) { \n for (int j=i+1; j<n; j++) {\n long long int num = a[i];\n num *= a[j];\n if (perfectSquare(num)) {\n ans += frequency[squareRoot(num)];\n }\n }\n }\n return ans;\n }\n \n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n return findTriplets(nums1, nums2) + findTriplets(nums2, nums1);\n }\n};\n```
6
0
[]
2
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
2 pointer approach || O(1) space complexity || 98% faster
2-pointer-approach-o1-space-complexity-9-n4s9
\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n Arrays.sort(nums1);\n Arrays.sort(nums2);\n return count(nums1
harshitgoel1110
NORMAL
2021-06-26T13:08:12.317898+00:00
2021-06-26T13:08:12.317941+00:00
469
false
```\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n Arrays.sort(nums1);\n Arrays.sort(nums2);\n return count(nums1 , nums2) + count(nums2 , nums1);\n }\n \n public int count(int a[] , int b[]){\n int n = a.length;\n int m = b.length;\n int count = 0;\n for(int i=0;i<n;i++){\n long x = (long)a[i]*a[i];\n int j = 0;\n int k = m-1;\n while(j<k){\n long prod = (long)b[j]*b[k];\n if(prod<x)\n j++;\n else if(prod>x)\n k--;\n else if(b[j] != b[k]){\n int jNew = j;\n int kNew = k;\n \n while(b[j] == b[jNew])\n jNew++;\n while(b[k] == b[kNew])\n kNew--;\n count += (jNew-j)*(k-kNew);\n j = jNew;\n k = kNew;\n }\n else{\n int q = k-j+1;\n count += (q)*(q-1)/2;\n break;\n }\n }\n }\n return count;\n }\n \n}\n```
5
1
['Two Pointers', 'Java']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++||Two Pointers||Easy to Understand
ctwo-pointerseasy-to-understand-by-retur-cnxx
```\nclass Solution {\npublic:\n int countTriplet(vector &nums1,vector &nums2)\n {\n int ans=0,left,right;\n unordered_map freq;\n fo
return_7
NORMAL
2022-09-04T20:48:27.635595+00:00
2022-09-04T20:48:27.635641+00:00
663
false
```\nclass Solution {\npublic:\n int countTriplet(vector<int> &nums1,vector<int> &nums2)\n {\n int ans=0,left,right;\n unordered_map<int,int> freq;\n for(auto &n:nums2)\n {\n freq[n]++;\n }\n for(int i=0;i<nums1.size();i++)\n {\n long long t=(long long)nums1[i]*nums1[i];\n left=0;\n right=nums2.size()-1;\n while(left<right)\n {\n long long temp=(long long)nums2[left]*nums2[right];\n if(t==temp)\n {\n if(nums2[left]==nums2[right])\n {\n ans+=(freq[nums2[left]]*(freq[nums2[left]]-1))/2;\n break;\n }\n ans+=freq[nums2[left]]*freq[nums2[right]];\n left+=freq[nums2[left]];\n right-=freq[nums2[right]];\n }\n else if(t>temp)\n {\n left+=freq[nums2[left]];\n }\n else\n {\n right-=freq[nums2[right]];\n }\n }\n }\n return ans;\n }\n int numTriplets(vector<int>& nums1, vector<int>& nums2)\n {\n sort(nums1.begin(),nums1.end());\n sort(nums2.begin(),nums2.end());\n return countTriplet(nums1,nums2)+countTriplet(nums2,nums1);\n \n }\n};\n//if you like the solution plz upvote.
4
0
['Two Pointers', 'C']
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++, 20ms, 12MB, max(O(n1+n2), O(d1*d2)) (d1, d2 are number of distinct numbers in nums1 and nums2)
c-20ms-12mb-maxon1n2-od1d2-d1-d2-are-num-jv7q
Firstly we count how many times each number appeared in each vector.\n\nFor each distinct number n1 in one set, we try to find in the other set:\n 1. n2 == n1
alvin-777
NORMAL
2020-09-06T05:27:06.510237+00:00
2020-09-06T06:32:50.219446+00:00
601
false
Firstly we count how many times each number appeared in each vector.\n\nFor each distinct number n1 in one set, we try to find in the other set:\n 1. `n2 == n1` and n2 appeared at least twice\n 2. `n2 < n1` and exists n2x that `n2*n2x == n1*n1` => `n2x == n1*n1/n2`\n\nFor `1`, if n1 appeared f1 times and n2 appeared f2 times, the total number of combinations is: `f1 * C(f2, 2)` = `f1 * (f2*(f2-1)/2)`\nFor `2`, if we can find both n2 and n2x, appeared f2 and f2x times respectively, the total number of combinations is: `f1 * (f2*f2x)` (note when n2 < n1, n2x > n1, we don\'t want to double count, so only check n2 < n1)\n\nWe count for type 1, switch them over and count for type 2, finally return the sum.\n\n----\n\nComplexity analysis:\n\n1. Counting number frequency is `O(n1 + n2)`\n2. Counting combinations, for each distinct number in one set, we check all numbers in the other set, then switch over and do it again: `O(freq1.size() * freq2.size() * 2)`, let d1=freq1.size(), d2=freq2.size() => `O(d1*d2)`\n\nEither `1` or `2` can take longer time, for example, if we have all same numbers like `[1,1,1,1,...,1,1]` and `[1,1,1,1,...,1,1]`, `1` takes much longer time than `2`. On the other hand if we have a lot of distinct numbers then `2` will be longer.\nSo the overall time complexity is `max(O(n1+n2), O(d1*d2))`.\n\nWe use 2 hash maps to store the frequencies, so space complexity is `O(d1+d2)`.\n\n```cpp\nint numTriplets(vector<int>& nums1, vector<int>& nums2) {\n unordered_map<int64_t, int> freq1, freq2;\n for (int n : nums1) freq1[n]++;\n for (int n : nums2) freq2[n]++;\n\n auto Count = [](unordered_map<int64_t, int> &freqX, unordered_map<int64_t, int> &freqY) {\n int cnt = 0;\n for (auto [n1, f1] : freqX) {\n int c = 0;\n int64_t n1sq = n1*n1;\n for (auto [n2, f2] : freqY) {\n if (n2 == n1) {\n if (f2 > 1) c += f2*(f2 - 1)/2;\n } else if (n2 < n1 && n1sq % n2 == 0) {\n int n2x = n1sq/n2;\n if (freqY.count(n2x)) c += f2*freqY[n2x];\n }\n }\n cnt += c*f1;\n }\n return cnt;\n };\n\n return Count(freq1, freq2) + Count(freq2, freq1);\n}\n```\n
4
1
['C']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
5 LINE JAVA SOLUTION USING HASHMAP WITH EXPLANATION
5-line-java-solution-using-hashmap-with-zh5ux
1. Store the value of num1*num1 from the first Array in a map.\n2. Using two for loops generate all possible combination of num2 and check if the set contains t
visnunathan
NORMAL
2020-09-06T04:38:18.290999+00:00
2020-09-06T06:36:24.865667+00:00
444
false
**1. Store the value of num1*num1 from the first Array in a map.\n2. Using two for loops generate all possible combination of num2 and check if the set contains those value.\n3. If it contains add it to the sum and return it.**\n```\npublic int calculate(int[] num1, int[] num2) {\n HashMap<Long, Integer> map = new HashMap<>();\n long n = num1.length, m = num2.length, ans = 0;\n for(int i=0; i<n; i++) map.put((long)num1[i]*num1[i],map.getOrDefault((long)num1[i]*num1[i],0)+1);\n for(int j=0; j<m; j++) for(int k=j+1; k<m; k++) ans += (long)map.getOrDefault((long)num2[j]*num2[k],0);\n return (int)ans;\n }\n public int numTriplets(int[] nums1, int[] nums2) {\n return calculate(nums1,nums2) + calculate(nums2,nums1);\n }\n```
4
1
['Java']
2
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++ code using unordered_map
c-code-using-unordered_map-by-shalinipan-j93h
\nclass Solution {\npublic:\n int get(vector<int>& nums1, vector<int>& nums2)\n {\n unordered_map<long long int,long long int>m;int ans=0;\n
shalinipandey1955
NORMAL
2020-09-06T06:41:04.916228+00:00
2020-10-26T10:29:34.139047+00:00
158
false
```\nclass Solution {\npublic:\n int get(vector<int>& nums1, vector<int>& nums2)\n {\n unordered_map<long long int,long long int>m;int ans=0;\n for(int i=0;i<nums1.size();i++)\n {\n m[(long long )nums1[i]*nums1[i]]++;\n }\n for(int i=0;i<nums2.size();i++)\n {\n for(int j=i+1;j<nums2.size();j++)\n {\n if(m.find((long long)nums2[i]*nums2[j])!=m.end())ans+=m[(long long)nums2[i]*nums2[j]];\n }\n }return ans;\n }\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n return get(nums1,nums2)+get(nums2,nums1);}\n}; \n```
3
1
['C']
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
[C++] Explanation, Approach and Code and Time Complexity
c-explanation-approach-and-code-and-time-80n5
Approach\n 0. Sort the arrays since you need to search\n For type 1:\n\t\n 1. select first number from nums1\n 2. Square it\n 3. Select number fr
rahulanandyadav2000
NORMAL
2020-09-06T04:13:10.557620+00:00
2020-09-06T04:33:27.322417+00:00
474
false
Approach\n 0. Sort the arrays since you need to search\n For type 1:\n\t\n 1. select first number from nums1\n 2. Square it\n 3. Select number from nums2 and divide it by square of nums1[i]\n 4. If divisible, search for all occurences of the other pair in nums2\n 5. Lets there be x occurences then add x to ans.\n 6. But the intresting thing to note is if the numbers selected in nums2 is square root of \n number selected in nums1 then we have one extra occurence, so subtract one from answer.\n \nRepeat this for type 2.\nFinally return answer.\n\nSince we sort the array use upper_bound and lower_bound to search in log(n);\n\nOverall time Complexity =mlog(n)+nlog(m)\nwhich is overall nlog(n)\n\n```\nclass Solution\n{\npublic:\n int count(vector<int> &arr, long long int x, int n)\n {\n\n auto low = lower_bound(arr.begin(), arr.end(), x);\n if (low == arr.end() || *low != x)\n return 0;\n auto high = upper_bound(low, arr.end(), x);\n return high - low;\n }\n\n int numTriplets(vector<int> &nums1, vector<int> &nums2)\n {\n int m = nums1.size();\n int n = nums2.size();\n int i, j;\n sort(nums1.begin(), nums1.end());\n sort(nums2.begin(), nums2.end());\n int trip = 0;\n for (i = 0; i < m; i++)\n {\n long long toSearch = (long long)nums1[i] * (long long)nums1[i];\n for (j = 0; j < n; j++)\n {\n long long int num1 = nums2[j];\n if (toSearch % num1 == 0)\n {\n\n int c = count(nums2, toSearch / num1, n);\n if (c > 0)\n trip += c;\n if (num1 * num1 == toSearch)\n trip -= 1;\n }\n }\n }\n for (i = 0; i < n; i++)\n {\n long long toSearch = (long long)nums2[i] * (long long)nums2[i];\n for (j = 0; j < m; j++)\n {\n long long int num1 = nums1[j];\n if (toSearch % num1 == 0)\n {\n\n int c = count(nums1, toSearch / num1, m);\n if (c > 0)\n trip += c;\n if (num1 * num1 == toSearch)\n trip -= 1;\n }\n }\n }\n return trip / 2;\n }\n};
3
0
['C', 'Binary Tree']
2
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Rust || Simple solution
rust-simple-solution-by-user7454af-aql2
Complexity\n- Time complexity: O(n^2)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n^2)\n Add your space complexity here, e.g. O(n) \n\n
user7454af
NORMAL
2024-06-06T17:09:17.135202+00:00
2024-06-06T17:09:17.135238+00:00
29
false
# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nuse std::collections::HashMap;\nimpl Solution {\n pub fn num_triplets(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {\n let nums1 = nums1.iter().map(|&n| n as i64).collect::<Vec<_>>();\n let nums2 = nums2.iter().map(|&n| n as i64).collect::<Vec<_>>();\n let mut products = HashMap::new();\n for j in 0..nums1.len() {\n for k in j+1..nums1.len() {\n *products.entry(nums1[j]*nums1[k]).or_insert(0) += 1;\n }\n }\n let mut ans = 0;\n for &n in nums2.iter() {\n ans += *products.get(&(n*n)).unwrap_or(&0);\n }\n products.clear();\n for j in 0..nums2.len() {\n for k in j+1..nums2.len() {\n *products.entry(nums2[j]*nums2[k]).or_insert(0) += 1;\n }\n }\n for &n in nums1.iter() {\n ans += *products.get(&(n*n)).unwrap_or(&0);\n }\n ans\n }\n}\n```
2
0
['Rust']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
[Python 3] O(MN) short and concise
python-3-omn-short-and-concise-by-gabhay-bogn
\tclass Solution:\n\t\tdef numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n\t\t\tdef get_res(a,b):\n\t\t\t\tres,n=0,len(b)\n\t\t\t\tprod=Counter(
gabhay
NORMAL
2022-07-22T05:06:43.091470+00:00
2022-07-22T05:06:43.091508+00:00
295
false
\tclass Solution:\n\t\tdef numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n\t\t\tdef get_res(a,b):\n\t\t\t\tres,n=0,len(b)\n\t\t\t\tprod=Counter([x*x for x in a])\n\t\t\t\tfor i in range(n):\n\t\t\t\t\tfor j in range(i+1,n):\n\t\t\t\t\t\tres+=prod[b[i]*b[j]]\n\t\t\t\treturn res\n\t\t\treturn get_res(nums1,nums2)+get_res(nums2,nums1)
2
0
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Brute force approach | C++
brute-force-approach-c-by-tusharbhart-ifn5
\nclass Solution {\npublic:\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n \n unordered_map<long, int> m1, m2;\n for(int
TusharBhart
NORMAL
2022-02-28T08:25:12.432454+00:00
2022-02-28T08:25:12.432484+00:00
271
false
```\nclass Solution {\npublic:\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n \n unordered_map<long, int> m1, m2;\n for(int i : nums1) m1[(long long)i*i]++;\n for(int i : nums2) m2[(long long)i*i]++;\n \n int ans = 0;\n \n for(int i=0; i<nums2.size()-1; i++){\n for(int j=i+1; j<nums2.size(); j++){\n if(m1[(long long)nums2[i] * nums2[j]]){\n ans += m1[(long long)nums2[i] * nums2[j]];\n }\n }\n }\n for(int i=0; i<nums1.size()-1; i++){\n for(int j=i+1; j<nums1.size(); j++){\n if(m2[(long long)nums1[i] * nums1[j]]){\n ans += m2[(long long)nums1[i] * nums1[j]];\n }\n }\n }\n return ans; \n }\n};\n```
2
0
['C']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Python intuitive hashmap solution, O(n*m) time
python-intuitive-hashmap-solution-onm-ti-cpqi
\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n sqr1, sqr2 = defaultdict(int), defaultdict(int)\n m, n
byuns9334
NORMAL
2021-12-31T09:31:31.364955+00:00
2021-12-31T09:31:31.364991+00:00
419
false
```\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n sqr1, sqr2 = defaultdict(int), defaultdict(int)\n m, n = len(nums1), len(nums2)\n for i in range(m):\n sqr1[nums1[i]**2] += 1\n for j in range(n):\n sqr2[nums2[j]**2] += 1\n \n res = 0 \n for i in range(m-1):\n for j in range(i+1, m):\n if nums1[i]*nums1[j] in sqr2:\n res += sqr2[nums1[i]*nums1[j]]\n \n for i in range(n-1):\n for j in range(i+1, n):\n if nums2[i]*nums2[j] in sqr1:\n res += sqr1[nums2[i]*nums2[j]]\n return res\n```
2
0
['Python', 'Python3']
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C+ (A very simple Two Sum like approach)
c-a-very-simple-two-sum-like-approach-by-5psp
\n//Approach-1 (Simple solution)\nclass Solution {\npublic:\n void twoProduct(ull target, vector<int> & nums, int &count) {\n unordered_map<int, int>
mazhar_mik
NORMAL
2021-06-30T02:05:48.952274+00:00
2021-06-30T02:22:11.825408+00:00
276
false
```\n//Approach-1 (Simple solution)\nclass Solution {\npublic:\n void twoProduct(ull target, vector<int> & nums, int &count) {\n unordered_map<int, int> mp;\n mp[1] = 0;\n for(int i = 0; i<nums.size(); i++) {\n if(target%nums[i] == 0) {\n int remain= target/nums[i];\n count += mp[remain];\n }\n mp[nums[i]]++;\n }\n }\n\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n int n1 = nums1.size();\n int n2 = nums2.size();\n \n int count = 0;\n for(int i = 0; i<n1; i++) {\n twoProduct((long)nums1[i]*nums1[i], nums2, count);\n }\n \n for(int i = 0; i<n2; i++) {\n twoProduct((long)nums2[i]*nums2[i], nums1, count);\n }\n \n return count;\n }\n};\n```\n\n```\n//Approach-2 (Using C++ STL for a concise code)\n//However the concept of both solution are exactly same.\n//This approach just teaces on how to use STL in C++ to make life easy\n\nclass Solution {\npublic:\n int twoProduct(long target, vector<int> &nums) {\n unordered_map<int, int> mp;\n int count = 0;\n \n for(int &x : nums) {\n if(target%x == 0) {\n count += mp[target/x];\n }\n mp[x]++;\n }\n return count;\n }\n\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n auto lambda1 = [&](int s, long n) {\n return s + twoProduct(n*n, nums2);\n };\n\n auto lambda2 = [&](int s, long n) {\n return s + twoProduct(n*n, nums1);\n };\n\n return accumulate(begin(nums1), end(nums1), 0, lambda1) +\n accumulate(begin(nums2), end(nums2), 0, lambda2);\n }\n};\n```
2
0
[]
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
JavaScript Solution
javascript-solution-by-deadication-tzn9
\nvar numTriplets = function(nums1, nums2) {\n const squaredFreq1 = countSquareFreq(nums1);\n const squaredFreq2 = countSquareFreq(nums2);\n \n retu
Deadication
NORMAL
2021-04-26T16:48:27.417270+00:00
2021-04-26T16:55:12.777276+00:00
140
false
```\nvar numTriplets = function(nums1, nums2) {\n const squaredFreq1 = countSquareFreq(nums1);\n const squaredFreq2 = countSquareFreq(nums2);\n \n return countProdFreq(nums1, squaredFreq2) + countProdFreq(nums2, squaredFreq1);\n\t\n \n function countSquareFreq(nums) {\n const freq = new Map();\n \n for (const num of nums) {\n const squared = num * num;\n \n if (!freq.has(squared)) freq.set(squared, 0);\n freq.set(squared, freq.get(squared) + 1);\n }\n \n return freq;\n }\n \n function countProdFreq(nums, freqMap) {\n let count = 0;\n \n for (let i = 0; i < nums.length - 1; i++) {\n for (let j = i + 1; j < nums.length; j++) {\n const prod = nums[i] * nums[j];\n \n if (freqMap.has(prod)) count += freqMap.get(prod);\n }\n }\n \n return count;\n }\n};\n```
2
0
['Hash Table', 'JavaScript']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Java O(n * sqrt(n)) solution using prime factorisation
java-on-sqrtn-solution-using-prime-facto-khkc
Take the example \nnums1 -> [4]\nnums2 -> [2,2,2,4,4,8,8]\nfor the SqrNo = 16, possible 2 pairs of factors are (1,16) (2,8) (4,4)\nHave a count hashmap of all c
tywin_lannister97
NORMAL
2021-03-14T16:54:01.930850+00:00
2021-03-14T16:54:01.930887+00:00
188
false
Take the example \nnums1 -> [4]\nnums2 -> [2,2,2,4,4,8,8]\nfor the SqrNo = 16, possible 2 pairs of factors are (1,16) (2,8) (4,4)\nHave a count hashmap of all count nos and simply check for all these cases. Repeat the same for each of nums2 combination against num1. One edge case is int overflow if n= 10^5 n ^ 2 will cause overflow, so use long type\nTime Complexity O(n * sqrt(n) + m * sqrt(m)) where n and m are sizes of num1 and num2 respectively.\n```\npublic int numTriplets(int[] nums1, int[] nums2) {\n HashMap<Long, Integer> nums1Count = new HashMap<>();\n HashMap<Long, Integer> nums2Count = new HashMap<>();\n for (int n : nums1) {\n nums1Count.put((long) n, nums1Count.getOrDefault((long) n, 0) + 1);\n }\n for (int n : nums2) {\n nums2Count.put((long) n, nums2Count.getOrDefault((long) n, 0) + 1);\n }\n int res = 0;\n for (int n : nums1) {\n long sqr = (long) n * n;\n res += findPairs(sqr, nums2Count);\n }\n for (int n : nums2) {\n long sqr = (long) n * n;\n res += findPairs(sqr, nums1Count);\n }\n return res;\n }\n\n private int findPairs(long sqrNumber, HashMap<Long, Integer> map) {\n int count = 0;\n for (long i = 1; i * i <= sqrNumber; i++) {\n if (sqrNumber % i == 0 && map.containsKey(i) && map.containsKey(sqrNumber / i)) {\n if (i == sqrNumber / i) {\n //sqr no ==> 16. array elements => 4,4,4,4 pairs ==> (3+2+1) sum of n numbers (n * (n+1))/2\n int totalVal = map.get(i) - 1;\n count += ((totalVal * (totalVal + 1)) / 2);\n } else {\n //sqrNo ==> 16, combination=2*8 array elements => 2,2,8,8,8 => totalPairs => 2 * 3\n int multiplicandCount = map.get(i);\n int multiplierCount = map.get(sqrNumber / i);\n count += (multiplicandCount * multiplierCount);\n }\n }\n }\n return count;\n }\n\n```
2
2
[]
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
93%/91% Python3, Hash table
9391-python3-hash-table-by-awong05-b49z
\nfrom collections import Counter\n\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n def helper(A, B):\n
awong05
NORMAL
2020-09-17T13:17:44.056126+00:00
2020-09-17T13:17:44.056162+00:00
160
false
```\nfrom collections import Counter\n\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n def helper(A, B):\n ans = 0\n C = Counter([a*a for a in A])\n D = Counter()\n for b in B:\n for k, v in D.items():\n if k*b in C:\n ans += v * C[k*b]\n D[b] += 1\n return ans\n \n return helper(nums1, nums2) + helper(nums2, nums1)\n```
2
0
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
[Python] Using counter O(n*m)
python-using-counter-onm-by-carloscerlir-0xay
\n def numTriplets(self, A: List[int], B: List[int]) -> int:\n def getTriplets(A, B):\n m, n = len(A), len(B)\n ans = 0\n
carloscerlira
NORMAL
2020-09-06T04:07:13.144072+00:00
2020-09-06T04:20:32.859520+00:00
151
false
```\n def numTriplets(self, A: List[int], B: List[int]) -> int:\n def getTriplets(A, B):\n m, n = len(A), len(B)\n ans = 0\n counter = Counter()\n for j in range(n):\n for k in range(j+1,n):\n prod = B[j]*B[k]\n counter[prod] += 1\n for i in range(m):\n prod = A[i]**2\n ans += counter[prod]\n return ans \n return getTriplets(A,B) + getTriplets(B,A)\n```
2
0
['Python']
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
[Java] Use Hashmap to Maintain Frequencies O(N^2 + M^2)
java-use-hashmap-to-maintain-frequencies-zgwa
\n public int numTriplets(int[] nums1, int[] nums2) {\n HashMap<Long, Integer> s1 = new HashMap();\n HashMap<Long, Integer> s2 = new HashMap();
yuhwu
NORMAL
2020-09-06T04:06:37.134275+00:00
2020-09-06T04:06:37.134341+00:00
141
false
```\n public int numTriplets(int[] nums1, int[] nums2) {\n HashMap<Long, Integer> s1 = new HashMap();\n HashMap<Long, Integer> s2 = new HashMap();\n int n1 = nums1.length;\n int n2 = nums2.length;\n for(int i=0; i<n1; i++){\n for(int j=i+1; j<n1; j++){\n long cur = (long)nums1[i]*nums1[j];\n s1.put(cur, s1.getOrDefault(cur, 0)+1);\n }\n }\n for(int i=0; i<n2; i++){\n for(int j=i+1; j<n2; j++){\n long cur = (long)nums2[i]*nums2[j];\n s2.put(cur, s2.getOrDefault(cur, 0)+1);\n }\n }\n int res = 0;\n for(int num : nums1){\n res+=s2.getOrDefault((long)num*num, 0);\n }\n for(int num : nums2){\n res+=s1.getOrDefault((long)num*num, 0);\n }\n return res;\n }\n```
2
1
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++ Easy 3 Sum, 2 pointer (with comments) | O(N*M) time O(1) space
c-easy-3-sum-2-pointer-with-comments-onm-0y1u
\n\nclass Solution {\npublic:\n #define ll long long\n \n\t// returns count of valids triplets (i, j, K) of type 1\n\t// note that to find of type 2, just
chwanshu27
NORMAL
2020-09-06T04:04:49.667232+00:00
2020-09-06T04:24:55.401567+00:00
172
false
```\n\nclass Solution {\npublic:\n #define ll long long\n \n\t// returns count of valids triplets (i, j, K) of type 1\n\t// note that to find of type 2, just swap nums1 and nums2 while calling \n int returnCount(vector<int>& nums1, vector<int>& nums2) {\n int n = nums1.size(), m = nums2.size();\n int count = 0;\n \n for(int k=0; k<n; k++) {\n ll target = nums1[k]*1ll*nums1[k];\n\t\t\t// we\'ll find two numbers in nums2 such that their product equals target \n int i=0, j=m-1;\n while(i<j) {\n ll prod = nums2[i]*1ll*nums2[j];\n if(prod == target) {\n\t\t\t\t\t// case 1 : nums[i] == nums[j]\n\t\t\t\t\t// this means all numbers in between i & j are same and\n\t\t\t\t\t// we can choose any two out of all of them, hence Nc2 possibilities\n if(nums2[i] == nums2[j]) {\n int len = j-i+1;\n count += len*(len-1)/2;\n i = j+1;\n }\n\t\t\t\t\t// case 2 : if not so\n\t\t\t\t\t// find the number of elements equal to nums2[i] (say n1) and\n\t\t\t\t\t// that equal to nums2[j] ( ssay n2)\n\t\t\t\t\t// add n1*n2 to ans\n else {\n int left_len = 1, right_len = 1;\n while(i<j && nums2[i] == nums2[i+1]) {\n i++;\n left_len++;\n }\n while(j>i && nums2[j-1] == nums2[j]) {\n j--;\n right_len++;\n }\n \n count += left_len * right_len;\n i++; j--;\n }\n \n }\n\t\t\t\t// accordingly move pointer i or j\n else if(prod < target)\n i++;\n else\n j--;\n }\n }\n \n return count;\n }\n \n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n \n sort(nums1.begin(), nums1.end());\n sort(nums2.begin(), nums2.end());\n \n return returnCount(nums1, nums2) + returnCount(nums2, nums1);\n \n }\n};\n\n\n```
2
0
['Two Pointers', 'C']
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Python3 Solution
python3-solution-by-deleted_user-k82m
python\ndef numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n\trev, n1, n2 = 0, Counter(nums1), Counter(nums2)\n\n\tfor i in range(len(nums1)-1):\
deleted_user
NORMAL
2020-09-06T04:02:50.377735+00:00
2020-09-06T04:02:50.377837+00:00
376
false
```python\ndef numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n\trev, n1, n2 = 0, Counter(nums1), Counter(nums2)\n\n\tfor i in range(len(nums1)-1):\n\t\tfor j in range(i+1, len(nums1)):\n\t\t\tt = (nums1[i] * nums1[j])**(1/2)\n\n\t\t\tif t == int(t) and t in n2:\n\t\t\t\trev += n2[t]\n\n\tfor i in range(len(nums2)-1):\n\t\tfor j in range(i+1, len(nums2)):\n\t\t\tt = (nums2[i] * nums2[j])**(1/2)\n\n\t\t\tif t == int(t) and t in n1:\n\t\t\t\trev += n1[t]\n\n\treturn rev\n```
2
0
['Python', 'Python3']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Easy Java Solution Using HashMap
easy-java-solution-using-hashmap-by-ravi-0faf
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
ravikumar50
NORMAL
2023-08-05T10:55:36.027232+00:00
2023-08-05T10:55:36.027260+00:00
34
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# Code\n```\nclass Solution {\n public int numTriplets(int[] arr1, int[] arr2) {\n int n1 = arr1.length;\n int n2 = arr2.length;\n\n HashMap<Long,Integer> hp1 = new HashMap<>();\n HashMap<Long,Integer> hp2 = new HashMap<>();\n\n for(int i=0; i<n1; i++){\n long a = (long)arr1[i]*(long)arr1[i];\n if(hp1.containsKey(a)) hp1.put(a,hp1.get(a)+1);\n else hp1.put(a,1);\n }\n\n for(int i=0; i<n2; i++){\n long a = (long)arr2[i]*(long)arr2[i];\n if(hp2.containsKey(a)) hp2.put(a,hp2.get(a)+1);\n else hp2.put(a,1);\n }\n\n\n int ans = 0;\n\n for(int i=0; i<n1; i++){\n for(int j=i+1; j<n1; j++){\n long a = (long)arr1[i]*(long)arr1[j];\n if(hp2.containsKey(a)){\n ans=ans+hp2.get(a);\n }\n }\n }\n\n for(int i=0; i<n2; i++){\n for(int j=i+1; j<n2; j++){\n long a = (long)arr2[i]*(long)arr2[j];\n if(hp1.containsKey(a)){\n ans=ans+hp1.get(a);\n }\n }\n }\n\n return ans;\n }\n}\n```
1
0
['Java']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++ || Easy Explanation ||O(N^2)
c-easy-explanation-on2-by-avi1273619-i2r7
// long long temp,t,help are used to keep the product within limits (prevent overflow)\n \n// The idea is to store all the squares in a map(not se
avi1273619
NORMAL
2022-08-06T13:39:36.526555+00:00
2023-01-15T12:45:32.302121+00:00
379
false
// long long temp,t,help are used to keep the product within limits (prevent overflow)\n \n// The idea is to store all the squares in a map(not set because duplicates may be present an dnot even multiset because we won\'t get the number of times the duplicates appears)\n \n// Use nested loop then and check which pairs product is present as square in another map and add its occurences\n \n int numTriplets(vector<int>& nums1, vector<int>& nums2) \n {\n map<long long,int> st1,st2; \n long long temp,t;\n for(int i=0;i<nums1.size();i++)\n {\n t=nums1[i];\n temp=t*t;\n \n \n \n st1[t*t]++;\n }\n \n for(int i=0;i<nums2.size();i++)\n {\n t=nums2[i];\n temp=t*t;\n \n \n st2[t*t]++;\n }\n \n int cnt=0;\n long long help1,help2;\n for(int i=0;i<nums1.size();i++)\n {\n for(int j=i+1;j<nums1.size();j++)\n {\n help1=nums1[i];\n help2=nums1[j];\n temp=help1*help2;\n \n if(st2.find(temp)!=st2.end())\n {\n cnt+=st2[temp];\n }\n }\n }\n \n for(int i=0;i<nums2.size();i++)\n {\n for(int j=i+1;j<nums2.size();j++)\n {\n help1=nums2[i];\n help2=nums2[j];\n temp=help1*help2;\n \n \n if(st1.find(temp)!=st1.end())\n {\n cnt+=st1[temp];\n }\n }\n }\n return cnt;\n }
1
0
['C']
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
[Javascript] Two Approaches - Hashmap & Two Pointers
javascript-two-approaches-hashmap-two-po-3yp6
Solution 1: Hashmap\n\nThis approach is similar to the two sum problem.\nWe use a hashmap to keep track of the frequencies of past numbers.\nCount the number of
anna-hcj
NORMAL
2022-06-27T10:59:14.335469+00:00
2022-06-27T10:59:14.335512+00:00
142
false
**Solution 1: Hashmap**\n\nThis approach is similar to the two sum problem.\nWe use a hashmap to keep track of the frequencies of past numbers.\nCount the number of `target / nums2[j]` in the hashmap.\n\n`n = length of nums1`, `m = length of nums2`\nTime Complexity: `O(nm)` 498ms\nSpace Complexity: `O(n + m)` 48.3MB\n```\nvar numTriplets = function(nums1, nums2) {\n return getTriplets(nums1, nums2) + getTriplets(nums2, nums1);\n \n function getTriplets(nums1, nums2) {\n let ans = 0;\n for (let i = 0; i < nums1.length; i++) {\n let target = nums1[i] * nums1[i], map = new Map();\n for (let j = 0; j < nums2.length; j++) {\n ans += map.get(target / nums2[j]) || 0;\n map.set(nums2[j], (map.get(nums2[j]) || 0) + 1);\n }\n }\n return ans;\n }\n};\n```\n\n\n**Solution 2: Three Pointers**\n\n1. Sort both arrays. This is so that we can use two pointers to calculate the pairs.\n2. For each `nums1[i] `\n Use two pointers (`start = 0`, `end = n - 1`) in `nums2`\n Count the number of pairs where `nums2[j] * nums2[k] === nums1[i] * nums1[i]`\n There are two special cases to consider:\n\n Case 1. `nums2[j] !== nums2[k]`.\n An array like `[1,1,3,3]`. \n Count the number of repeated `nums2[j]` and repeated `nums2[k]`.\n Multiply the two counts together to get the number of combinations.\n\n Case 2. `[nums2[j], ..., nums2[k]]` are all equal\n e.g: `[1,1,1,1,1]`\n For each `nums2[j]`, we can pair it with any number on the right.\n For the above example this would be: `4 + 3 + 2 + 1`\n Use the formula `(n-1)*n/2 `to calculate the sum of `1 + 2 + 3 + ... + n-1`\n\nTime Complexity: `O(nm + n log(n) + m log(m))` 153ms\nSpace Complexity: `O(log(n) + log(m))` (space for sorting) 43.1MB\n```\nvar numTriplets = function(nums1, nums2) {\n nums1.sort((a, b) => a - b);\n nums2.sort((a, b) => a - b);\n return calc(nums1, nums2) + calc(nums2, nums1);\n \n function calc(nums1, nums2) {\n let ans = 0;\n for (let i = 0; i < nums1.length; i++) {\n let target = nums1[i] * nums1[i];\n let j = 0, k = nums2.length - 1;\n while (j < k) {\n if (nums2[j] * nums2[k] === target) {\n if (nums2[j] === nums2[k]) { // case 2: [nums2[j], ..., nums2[k]] are all equal\n ans += (k - j) * (k - j + 1) / 2;\n j = k;\n } else { // case 1: nums2[j] !== nums2[k]\n let left = j, right = k;\n while (j < k && nums2[j] === nums2[left]) j++;\n while (k >= 0 && nums2[k] === nums2[right]) k--;\n ans += (j - left) * (right - k);\n }\n }\n else if (nums2[j] * nums2[k] < target) j++;\n else k--;\n }\n }\n return ans;\n }\n};\n```
1
0
['JavaScript']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
python soln
python-soln-by-kumarambuj-6fg5
\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n hash1=defaultdict(int)\n hash2=defaultdict(int)\n
kumarambuj
NORMAL
2022-01-02T08:57:32.870500+00:00
2022-01-02T08:57:32.870530+00:00
114
false
```\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n hash1=defaultdict(int)\n hash2=defaultdict(int)\n \n for x in nums1:\n hash1[x*x]+=1\n \n for x in nums2:\n hash2[x*x]+=1\n \n res=0\n for i in range(len(nums1)-1):\n for j in range(i+1,len(nums1)):\n \n res+=hash2[nums1[i]*nums1[j]]\n \n for i in range(len(nums2)-1):\n for j in range(i+1,len(nums2)):\n \n res+=hash1[nums2[i]*nums2[j]]\n return res\n \n \n \n \n \n```
1
0
['Python']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++ Brute force | Using Hash_map
c-brute-force-using-hash_map-by-nitink_3-34c4
\n#define ll long long int\nclass Solution {\npublic:\n \n int find(vector<int>nums1,vector<int>nums2)\n {\n unordered_map<ll,ll>mp;\n //
HustlerNitin
NORMAL
2022-01-01T18:03:06.428556+00:00
2022-01-01T18:03:06.428602+00:00
392
false
```\n#define ll long long int\nclass Solution {\npublic:\n \n int find(vector<int>nums1,vector<int>nums2)\n {\n unordered_map<ll,ll>mp;\n // O(n^2)\n for(int i=0;i<nums2.size();i++)\n {\n for(int j=i+1;j<nums2.size();j++)\n {\n ll p=(long long)nums2[i]*nums2[j];\n mp[p]++;\n }\n }\n \n ll count=0;\n // square of a number\n for(int i=0;i<nums1.size();i++)\n {\n ll p=(long long)nums1[i]*nums1[i]; // square of num1\n if(mp.find(p)!=mp.end())\n {\n count+=mp[p];\n }\n }\n return count;\n }\n \n int numTriplets(vector<int>& nums1, vector<int>& nums2) \n {\n return find(nums1,nums2)+find(nums2,nums1);\n }\n};\n```\n**please hit upvote if you like it : )**
1
0
['C', 'C++']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++ BRUTEFORCE
c-bruteforce-by-the_expandable-p63f
```\nclass Solution {\npublic:\n #define ll long long int\n int numTriplets(vector& a, vector& b) {\n mapmp1;\n mapmp2;\n sort(a.begi
the_expandable
NORMAL
2021-09-23T04:57:11.768427+00:00
2021-09-23T04:57:11.768472+00:00
74
false
```\nclass Solution {\npublic:\n #define ll long long int\n int numTriplets(vector<int>& a, vector<int>& b) {\n map<ll,ll>mp1;\n map<ll,ll>mp2;\n sort(a.begin(),a.end());\n sort(b.begin(),b.end());\n for(int i = 0 ; i < a.size();i++)\n {\n ll p = (ll)a[i]*a[i];\n mp1[p]++;\n }\n for(int i = 0 ; i < b.size();i++)\n {\n ll p = (ll)b[i]*b[i];\n mp2[p]++;\n }\n ll ans = 0 ;\n for(int i = 0 ; i < b.size();i++)\n {\n for(int j=i+1;j<b.size();j++){\n ll p = (ll)b[i]*b[j];\n ans+=mp1[p];\n }\n }\n for(int i = 0 ; i < a.size();i++)\n {\n for(int j=i+1;j<a.size();j++){\n ll p = (ll)a[i]*a[j];\n ans+=mp2[p];\n }\n }\n return ans;\n }\n};
1
0
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Java solution
java-solution-by-keerthy0212-v0md
\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n return res(nums1,nums2)+res(nums2,nums1);\n }\n public static int res(i
keerthy0212
NORMAL
2021-05-09T17:08:20.012478+00:00
2021-05-09T17:08:20.012519+00:00
255
false
```\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n return res(nums1,nums2)+res(nums2,nums1);\n }\n public static int res(int[] nums1,int[] nums2)\n {\n int count=0;\n\t\tHashMap<Long,Integer> map=new HashMap<Long,Integer>();\n\t\tfor(long i:nums1)\n\t\t\tmap.put((i*i), map.getOrDefault(i*i,0)+1);\n\t\tfor(int i=0;i<nums2.length-1;i++)\n\t\t{\n\t\t\tfor(int j=i+1;j<nums2.length;j++)\n\t\t\t{\n\t\t\t\tlong prod=(long)nums2[i]*nums2[j];\n\t\t\t\tif(map.containsKey(prod))\n\t\t\t\t{\n\t\t\t\t\tcount=count+map.get(prod);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn count;\n }\n}\n```
1
0
['Java']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Python O(n^2) function
python-on2-function-by-dev-josh-b9jy
How do we approach such a question?\n You can try the brute force, but it will TLE\n I always try to fall back to the Two Sum problem\n\t Can we build dictionar
dev-josh
NORMAL
2021-02-16T19:02:26.161304+00:00
2021-02-16T19:11:19.360665+00:00
249
false
* How do we approach such a question?\n* You can try the brute force, but it will TLE\n* I always try to fall back to the **Two Sum problem**\n\t* Can we build dictionaries in linear or n^2 time to avoid n^3 time?\n\t\t* We can count the number of `nums1[i]^2` for example\n\t\t* We can also count the number of `nums2[j] * nums2[k]` too\n\t\t* Then, we can loop in linear time over the `nums1[i]^2` values, and access the count of `j * k` in O(1)\n\t\t* \n* **Ultimately, don\'t be afraid of having multiple `O(n)` loops**, or doing anytype of `k * O(n)` or `k * O(n^2)`.\n\t* The biggest concern is **reducing the upper bound** as much as possible, e.g, achieving `O(n^2)` instead of `O(n^3)`\n\n* So, next time, think of two sum, and see if you can have multiple loops (e.g `k * O(x)`) but reduce the upper bound, (`x` in this case) as much as possible!\n\n```python\nclass Solution:\n \n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n """\n O(n^2)\n """\n \n def check(nums1, nums2):\n \n # Initialize a dict: value->(value^2, count)\n a = {}\n for i in nums1:\n if i not in a:\n a[i] = [i**2, 1]\n else:\n a[i][-1] += 1\n \n # Initialize a dict: nums2[i] * nums[j] -> count\n b = collections.defaultdict(int)\n for i in range(len(nums2)):\n for j in range(i+1, len(nums2)):\n b[nums2[i]*nums2[j]] += 1\n \n # Calculate the result\n # result += i^2 count * j*k count for each combination\n result = 0 \n for (i, amount) in a.values(): \n result += b[i]*amount\n \n return result\n \n \n # Call above function twice\n return check(nums1, nums2) + check(nums2, nums1)\n```\n\n---\n\nIf you want to get a bit fancy, you can always spend time trying to optimize or clean up your code two \uD83D\uDE06\n\n```python\ndef calculate(a, b):\n square_counts = collections.Counter(i**2 for i in a)\n return sum(square_counts[b[j] * b[k]] for j in range(len(b)) for k in range(j+1, len(b)))\n\nreturn calculate(nums1, nums2) + calculate(nums2, nums1)\n```
1
0
['Python', 'Python3']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
[Python] Count, beats 100%, O(n * m)
python-count-beats-100-on-m-by-shoomoon-2jot
First count the elements in each array, then find the number of triplets for each element.\nIt is faster if there are lots of duplicates.\n\nclass Solution(obje
shoomoon
NORMAL
2021-01-28T18:22:59.641677+00:00
2021-01-28T18:22:59.641714+00:00
148
false
First count the elements in each array, then find the number of triplets for each element.\nIt is faster if there are lots of duplicates.\n```\nclass Solution(object):\n def numTriplets(self, nums1, nums2):\n """\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: int\n """\n cnt1 = collections.defaultdict(int)\n cnt2 = collections.defaultdict(int)\n for n in nums1:\n cnt1[n] += 1\n for n in nums2:\n cnt2[n] += 1\n\n def triplets(arr1, arr2):\n ans = 0\n for t, v in arr1.items():\n k = arr2.get(t, 0)\n tmp = k * (k - 1) // 2\n sq = t * t\n for m in arr2:\n if m < t and sq % m == 0:\n tmp += arr2.get(m, 0) * arr2.get(sq // m, 0)\n ans += tmp * v\n return ans\n return triplets(cnt1, cnt2) + triplets(cnt2, cnt1)\n```
1
0
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Python Solution Based on Binary Search And Memorization
python-solution-based-on-binary-search-a-ku2z
Time Complexity = O ( N * N * Log N )\n\n\n\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int: \n nums1.sort()\
pochy
NORMAL
2020-09-08T04:53:10.281496+00:00
2020-09-08T04:57:41.853257+00:00
184
false
Time Complexity = O ( N * N * Log N )\n\n\n```\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int: \n nums1.sort()\n nums2.sort()\n \n def lowerbound(target, left, right, nums):\n while left < right:\n mid = left + (right - left) // 2\n\n if nums[mid] == target:\n right = mid\n elif nums[mid] < target:\n left = mid + 1\n else:\n right = mid\n \n return left\n \n def higherbound(target, left, right, nums):\n while left < right:\n mid = left + (right - left) // 2\n \n if nums[mid] == target:\n left = mid + 1\n elif nums[mid] < target:\n left = mid + 1\n else:\n right = mid\n \n return left\n \n \n def helper(n, nums, memo):\n if n in memo:\n return memo[n]\n \n result = 0\n \n for i in range(len(nums)):\n if n % nums[i] != 0:\n continue\n \n target = n // nums[i]\n \n # find total number of target in nums[i+1:]\n lower = lowerbound(target, i+1, len(nums), nums)\n higher = higherbound(target, i+1, len(nums), nums)\n \n result += (higher - lower)\n \n memo[n] = result\n return result\n \n result = 0\n \n memo1 = {}\n for n in nums1:\n result += helper(n*n, nums2, memo1)\n \n memo2 = {}\n for n in nums2:\n result += helper(n*n, nums1, memo2)\n \n return result\n\n```
1
0
['Memoization', 'Binary Tree', 'Python', 'Python3']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Python3 3 liner - Number of Ways Where Square of Number Is Equal to Product of Two Numbers
python3-3-liner-number-of-ways-where-squ-67gh
\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n sq1 = Counter(map(mul, nums1, nums1))\n sq2 = Counter(m
r0bertz
NORMAL
2020-09-08T03:20:50.283602+00:00
2020-09-08T03:20:50.283656+00:00
166
false
```\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n sq1 = Counter(map(mul, nums1, nums1))\n sq2 = Counter(map(mul, nums2, nums2))\n return sum(sq2[a * b] for a, b in combinations(nums1, 2)) + sum(sq1[a * b] for a, b in combinations(nums2, 2))\n```
1
0
['Python', 'Python3']
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Java factorization solution O(n + m)
java-factorization-solution-on-m-by-igor-u92m
Algorithm:\n1. Create a map key: (num * num), value: count basing on first array\n2. Go throug the second array, for every number calculate a key containing fa
igor84
NORMAL
2020-09-07T14:24:28.135348+00:00
2020-09-07T15:58:39.652374+00:00
180
false
Algorithm:\n1. Create a map key: (num * num), value: count basing on first array\n2. Go throug the second array, for every number calculate a key containing factors that are represented odd number of times in number. For example, 60 is 2 * 2 * 3 * 5, the key is "3,5"\n3. Search for the values with the same key processed on previous iterations - they will form squares\n4. Check if the map based on the first array contains corresponding square. Update count if match is found\n5. Store store num under the same key\n\n<pre>\nclass Solution {\n // Cached factors\n private final Map&lt;Integer, Map&lt;Integer, Integer&gt;&gt; factorsCache = new HashMap&lt;&gt;();\n\n /*\n * Calculates factors for num. Returns a map where\n * key is prime factor, value is number of times the factor is used.\n *\n * For example, 60 will be represented as\n * 2 -&gt; 2\n * 3 -&gt; 1\n * 5 -&gt; 1\n */\n private Map&lt;Integer, Integer&gt; factors(int num) {\n Map&lt;Integer, Integer&gt; cached = factorsCache.get(num);\n if (cached != null) {\n // return cached value (if any)\n return cached;\n }\n\n // handle case num == 1 separately\n if (num == 1) {\n Map&lt;Integer, Integer&gt; ret = new HashMap&lt;&gt;();\n ret.put(1, 1);\n factorsCache.put(1, ret);\n return ret;\n }\n\n // calculate factors recursively\n for (int i = 2; i * i &lt;= num; i++) {\n if (num % i == 0) {\n Map&lt;Integer, Integer&gt; f1 = factors(i);\n Map&lt;Integer, Integer&gt; f2 = factors(num / i);\n\n Map&lt;Integer, Integer&gt; ret = new HashMap&lt;&gt;();\n for (Map.Entry&lt;Integer, Integer&gt; entry : f1.entrySet()) {\n Integer key = entry.getKey();\n Integer value = entry.getValue();\n ret.put(key, ret.getOrDefault(key, 0) + value);\n }\n for (Map.Entry&lt;Integer, Integer&gt; entry : f2.entrySet()) {\n Integer key = entry.getKey();\n Integer value = entry.getValue();\n ret.put(key, ret.getOrDefault(key, 0) + value);\n }\n\n factorsCache.put(num, ret);\n return ret;\n }\n }\n\n // cache the results\n Map&lt;Integer, Integer&gt; ret = new HashMap&lt;&gt;();\n ret.put(num, 1);\n factorsCache.put(num, ret);\n return ret;\n }\n\n public int numTriplets(int[] nums1, int[] nums2) {\n Map&lt;Long, Integer&gt; squaresMap1 = new HashMap&lt;&gt;();\n Map&lt;Long, Integer&gt; squaresMap2 = new HashMap&lt;&gt;();\n for (int n : nums1) {\n long sq = ((long) n) * n;\n squaresMap1.put(sq, squaresMap1.getOrDefault(sq, 0) + 1);\n }\n for (int n : nums2) {\n long sq = ((long) n) * n;\n squaresMap2.put(sq, squaresMap2.getOrDefault(sq, 0) + 1);\n }\n\n int ret = 0;\n\n // check nums1 against squares in nums2\n ret += count(nums1, squaresMap2);\n\n // check nums2 against squares in nums1\n ret += count(nums2, squaresMap1);\n\n return ret;\n }\n\n // cached keys\n private final Map&lt;Integer, String&gt; keyCache = new HashMap&lt;&gt;();\n\n /*\n * Key consists of factors (greater than 1) that are represented odd number of times in num\n * For example, 60 is 2 * 2 * 3 * 5, the key is "3,5"\n * 1 -&gt; ""\n * 2 -&gt; "2"\n * 3 -&gt; "3"\n * 4 -&gt; ""\n * 5 -&gt; "5"\n * 6 -&gt; "2,3"\n * ...\n */\n private String calculateKey(int num) {\n String cachedKey = keyCache.get(num);\n if (cachedKey != null) {\n return cachedKey;\n }\n\n String key = "";\n if (num &gt; 1) {\n Map&lt;Integer, Integer&gt; f = factors(num);\n List&lt;Integer&gt; list = new ArrayList&lt;&gt;();\n for (Map.Entry&lt;Integer, Integer&gt; entry : f.entrySet()) {\n if (entry.getValue() % 2 != 0) {\n list.add(entry.getKey());\n }\n }\n Collections.sort(list);\n StringBuilder sb = new StringBuilder();\n for (int j = 0; j &lt; list.size(); j++) {\n if (j &gt; 0) {\n sb.append(",");\n }\n sb.append(list.get(j));\n }\n key = sb.toString();\n }\n\n keyCache.put(num, key);\n\n return key;\n }\n\n\n private int count(int[] nums, Map&lt;Long, Integer&gt; complementary) {\n int ret = 0;\n\n // Examples:\n // key "3,5" -&gt;\n // 15 -&gt; 2 (number of times this value was seen previously)\n // 60 -&gt; 1 (number of times this value was seen previously)\n // key "3,7" -&gt;\n // 21 -&gt; 1 (number of times this value was seen previously)\n // 2100 -&gt; 4 (number of times this value was seen previously)\n Map&lt;String, Map&lt;Integer, Integer&gt;&gt; previousNumbers = new HashMap&lt;&gt;();\n\n for (int num : nums) {\n String key = calculateKey(num);\n\n // we need to find previously previously seen values with the same key\n // if current value is 60, the key is "3,5", every value that has the same key will represent a square,\n // 15, 60, 135 etc.\n Map&lt;Integer, Integer&gt; counts = previousNumbers.computeIfAbsent(key, k -&gt; new HashMap&lt;&gt;());\n for (Map.Entry&lt;Integer, Integer&gt; entry : counts.entrySet()) {\n Integer previous = entry.getKey();\n long product = previous.longValue() * num;\n\n // finding a match in the other array\n Integer complementaryCount = complementary.get(product);\n if (complementaryCount != null) {\n ret += entry.getValue() * complementaryCount;\n }\n }\n\n // recording current number in the map\n counts.put(num, counts.getOrDefault(num, 0) + 1);\n }\n\n return ret;\n }\n}\n</pre>
1
0
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++|| O(MN)||Easiest solution with self explanatory code
c-omneasiest-solution-with-self-explanat-fe11
Please Note that time complexity of find function in unordered_map is O(1)\n\nclass Solution {\npublic:\n int numTriplets(vector<int>& n1, vector<int>& n2) {
tejpratapp468
NORMAL
2020-09-07T05:56:06.468623+00:00
2020-09-07T05:58:59.159634+00:00
79
false
Please Note that time complexity of find function in unordered_map is O(1)\n```\nclass Solution {\npublic:\n int numTriplets(vector<int>& n1, vector<int>& n2) {\n int n=n1.size();int m=n2.size();\n long ans=0;\n //type 1\n for(int i=0;i<n;i++)\n {\n double a=n1[i];\n unordered_map<double,int> s;\n for(int j=0;j<m;j++)\n {\n double b=n2[j];\n double f=a*a/b;\n if(s.find(f)!=s.end()) ans+=s[f];\n s[b]++;\n }\n }\n //type 2\n for(int i=0;i<m;i++)\n {\n double a=n2[i];\n unordered_map<double,int> s;\n for(int j=0;j<n;j++)\n {\n double b=n1[j];\n double f=a*a/b;\n if(s.find(f)!=s.end()) ans+=s[f];\n s[b]++;\n }\n }\n return ans;\n }\n};\n```
1
0
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C# solution using Dictionary
c-solution-using-dictionary-by-pykan-g1du
\npublic int NumTriplets(int[] nums1, int[] nums2) {\n int w1 = GetWays(nums1, nums2);\n int w2 = GetWays(nums2, nums1);\n return w1 + w2;\
pykan
NORMAL
2020-09-06T09:13:30.698743+00:00
2020-09-11T13:48:20.834182+00:00
72
false
```\npublic int NumTriplets(int[] nums1, int[] nums2) {\n int w1 = GetWays(nums1, nums2);\n int w2 = GetWays(nums2, nums1);\n return w1 + w2;\n }\n \n public int GetWays(int[] nums1, int[] nums2) {\n int numWays = 0;\n long product = 0;\n \n Dictionary<long, int> d = new Dictionary<long, int>();\n for(int i = 0; i < nums1.Length; i++) {\n product = (long)nums1[i] * (long)nums1[i];\n if(d.ContainsKey(product))\n d[product]++;\n else {\n d.Add(product,1);\n }\n }\n \n for(int j = 0; j < nums2.Length-1; j++) {\n for(int k = j+1; k < nums2.Length; k++) {\n product = (long)nums2[j]*(long)nums2[k];\n if(d.ContainsKey(product)) {\n numWays += d[product];\n } \n }\n\n }\n \n return numWays;\n }\n \n```\n
1
0
[]
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Java Two Diff Solutions O(m^2+n^2) and O(m*n)
java-two-diff-solutions-om2n2-and-omn-by-gwdl
Method1: \n1. Use two different hashmaps\n2. Add entried to map for diff combinations of product\n3. Iterate over arrays and check if square of num exists in ot
meg20
NORMAL
2020-09-06T09:04:43.618580+00:00
2020-09-06T11:29:25.121585+00:00
116
false
Method1: \n1. Use two different hashmaps\n2. Add entried to map for diff combinations of product\n3. Iterate over arrays and check if square of num exists in other map\n\nTime: O(m^2 + n^2)\n```\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n Map<Long, Integer> productSet1 = new HashMap<>();\n Map<Long, Integer> productSet2 = new HashMap<>();\n int m = nums1.length, n = nums2.length;\n for(int i=0; i<m; i++) {\n for(int j=i+1; j<m; j++) {\n long product = (long) nums1[i]*nums1[j];\n productSet1.put(product, productSet1.getOrDefault(product, 0)+1);\n }\n }\n for(int i=0; i<n; i++) {\n for(int j=i+1; j<n; j++) {\n long product = (long) nums2[i]*nums2[j];\n productSet2.put(product, productSet2.getOrDefault(product, 0)+1);\n }\n }\n int count =0;\n for(int i=0; i<m; i++) {\n count+= productSet2.getOrDefault((long) nums1[i]*nums1[i], 0);\n }\n for(int i=0; i<n; i++) {\n count+= productSet1.getOrDefault((long) nums2[i]*nums2[i], 0);\n }\n return count;\n }\n}\n```\n\nMethod2: \n1. Sort both arrays\n2. Use a hashmap for two arrays to keep count of elements\n2. Use two pointer approach to look for any valid j and k indices in other array\n3. Take care of duplicates, via hashmap and update pointers\n\nTime: O(m*n)\n```\n public int findCount(int[] nums1, int[] nums2, Map<Integer, Integer> map) {\n int n=nums2.length, ans=0;\n for(int num: nums1) {\n int lo=0, hi=n-1;\n long target = (long) num*num;\n while(lo<hi) {\n long product = (long) nums2[lo]*nums2[hi];\n if(product<target) lo++;\n else if(product>target) hi--;\n else {\n int count1 = map.get(nums2[lo]);\n int count2 = map.get(nums2[hi]);\n if(nums2[lo]!=nums2[hi]) {\n ans+= count1*count2;\n } else {\n ans+= count1*(count1-1)/2;\n }\n while(lo<hi && nums2[lo]==nums2[lo+1]) lo++;\n while(hi>lo && nums2[hi]==nums2[hi-1]) hi--;\n lo++; hi--;\n }\n }\n }\n return ans;\n }\n \n public int numTriplets(int[] nums1, int[] nums2) {\n Arrays.sort(nums1);\n Arrays.sort(nums2);\n \n Map<Integer, Integer> map1 = new HashMap<>();\n Map<Integer, Integer> map2 = new HashMap<>();\n \n for(int num: nums1)\n map1.put(num, map1.getOrDefault(num, 0)+1);\n for(int num: nums2)\n map2.put(num, map2.getOrDefault(num, 0)+1);\n \n return findCount(nums1, nums2, map2) + findCount(nums2, nums1, map1);\n }\n}\n```
1
1
['Sorting', 'Java']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Java Bruteforce O(N^2)
java-bruteforce-on2-by-janap-fxi9
```\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n return getCount(nums1, getMap(nums2)) + getCount(nums2, getMap(nums1));\n
janap
NORMAL
2020-09-06T07:10:18.468508+00:00
2020-09-06T07:10:18.468564+00:00
43
false
```\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n return getCount(nums1, getMap(nums2)) + getCount(nums2, getMap(nums1));\n }\n \n Map<Long, Integer> getMap(int[] nums){\n Map<Long, Integer> map = new HashMap<>();\n for(long num: nums)\n map.put(num * num, map.getOrDefault(num * num,0)+1);\n return map;\n }\n \n int getCount(int[] nums, Map<Long, Integer> map){\n int count=0;\n for(int i=0;i<nums.length;i++){\n for(int j=i+1;j<nums.length;j++){\n long prod = (long)nums[i]*(long)nums[j];\n if(map.containsKey(prod))\n count += map.get(prod);\n }\n }\n return count;\n }\n}
1
0
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
c++ code using hashmap
c-code-using-hashmap-by-srjohn-312s
\nclass Solution {\npublic:\n unordered_map<double,int> hash1;\n unordered_map<double,int> hash2;\n int numTriplets(vector<int>& nums1, vector<int>& nu
srjohn
NORMAL
2020-09-06T06:56:50.249655+00:00
2020-09-06T06:56:50.249692+00:00
68
false
```\nclass Solution {\npublic:\n unordered_map<double,int> hash1;\n unordered_map<double,int> hash2;\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n for(int i=0;i<nums1.size();i++)\n {if(hash1.find(nums1[i])==hash1.end()) hash1[nums1[i]]=1;\n else hash1[nums1[i]]++; \n }\n for(int i=0;i<nums2.size();i++)\n {if(hash2.find(nums2[i])==hash2.end()) hash2[nums2[i]]=1;\n else hash2[nums2[i]]++;\n }\n\n int count=0;\n for(int i=0;i<nums2.size();i++){\n for(int j=i+1;j<nums2.size();j++){\n double p=sqrt((double)nums2[i]*(double)nums2[j]);\n if(hash1.find(p)!=hash1.end()) count=count+hash1[p];\n }\n }\n for(int i=0;i<nums1.size();i++){\n for(int j=i+1;j<nums1.size();j++){\n double p=sqrt((double)nums1[i]*(double)nums1[j]);\n if(hash2.find(p)!=hash2.end()) count=count+hash2[p];\n }\n }\n return count;\n }\n};\n```
1
1
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++ using 2 unordered_map
c-using-2-unordered_map-by-tejasrai-qvjx
\nclass Solution {\npublic:\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n int n=nums1.size();\n int m=nums2.size();\n uno
tejasrai
NORMAL
2020-09-06T06:18:00.064114+00:00
2020-09-06T06:19:30.796917+00:00
39
false
```\nclass Solution {\npublic:\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n int n=nums1.size();\n int m=nums2.size();\n unordered_map<long long int,long long int>s1;\n unordered_map<long long int,long long int>s2;\n int count=0;\n for(int i=0;i<n;i++)\n s1[(long long)nums1[i]*nums1[i]]++;\n for(int i=0;i<m;i++)\n s2[(long long) nums2[i]*nums2[i]]++;\n \n \n \n for(int i=0;i<m;i++){\n for(int j=i+1;j<m;j++){\n \n if(s1.find((long long)nums2[i]*nums2[j])!=s1.end())\n \n count+=(s1[(long long)nums2[i]*nums2[j]]);\n \n }\n }\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n if(s2.find((long long)nums1[i]*nums1[j])!=s2.end())count+=(s2[(long long)nums1[i]*nums1[j]]);\n \n }\n \n }return count;\n }\n};\n```
1
1
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Why 91/92 TCs passed? Please suggest/help.
why-9192-tcs-passed-please-suggesthelp-b-n7nh
\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n Arrays.sort(nums1);\n Arrays.sort(nums2);\n \n int ans
vvbhandare
NORMAL
2020-09-06T04:19:38.592012+00:00
2020-09-06T04:30:04.838119+00:00
155
false
```\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n Arrays.sort(nums1);\n Arrays.sort(nums2);\n \n int ans = 0;\n int n1 = nums1.length, n2 = nums2.length;\n Map<Long, Integer> S1 = new HashMap<>();\n Map<Long, Integer> S2 = new HashMap<>();\n \n for (int i = 0; i < n1; i++) {\n long s1 = (nums1[i] * nums1[i]);\n S1.put(s1, S1.getOrDefault(s1, 0) + 1);\n }\n // System.out.println("S1 = " + S1);\n \n for (int i = 0; i < n2; i++) {\n long s2 = ((long)nums2[i] * (long)nums2[i]);\n S2.put(s2, S2.getOrDefault(s2, 0) + 1);\n }\n // System.out.println("S2 = " + S2);\n \n for (int j = 0; j < n2; j++) {\n for (int k = j + 1; k < n2; k++) {\n long mul = ((long)nums2[j] * (long)nums2[k]);\n // System.out.println(nums2[j] + " " + nums2[k] + " = " + mul);\n if (S1.containsKey(mul)) {\n ans += S1.get(mul);\n }\n }\n }\n \n for (int j = 0; j < n1; j++) {\n for (int k = j + 1; k < n1; k++) {\n long mul = ((long)nums1[j] * (long)nums1[k]);\n // System.out.println(nums1[j] + " * " + nums1[k] + " = " + mul);\n if (S2.containsKey(mul)) {\n ans += S2.get(mul);\n }\n }\n }\n \n return ans;\n }\n}\n```\n\n1 blunder as not converted square elements into long. As mentioned below also corrected answer.\n\n**long s1 = ((long)nums1[i] * (long)nums1[i]);**
1
0
['Sorting']
2
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Easy Python Solution with proper and easy explanation
easy-python-solution-with-proper-and-eas-wlev
Okay so I followed a really simple stragegy:\nI created 2 dictionaries and put up the squared values of all the numbers in both the nums array in seperate dicti
shubhitt
NORMAL
2020-09-06T04:10:51.851297+00:00
2020-09-06T04:10:51.851332+00:00
59
false
Okay so I followed a really simple stragegy:\nI created 2 dictionaries and put up the squared values of all the numbers in both the nums array in seperate dictionaries, with their count\nNow I traverse both the arrays seperately and find out pairs such that, if the pair product is in the opposite dictionary, i.e, if I am looking for pairs in nums2 then i chech the values in ds1(dictionary for nums1 squared values) \nsimilarly for nums1 as well, this is really easy\n```\n\t\tds1 = dict()\n ds2 = dict()\n \n for i in nums1:\n val = i*i\n ds1[val] = ds1.get(val, 0) + 1\n \n for i in nums2:\n val = i*i\n ds2[val] = ds2.get(val, 0) + 1\n \n ans = 0\n \n for i in range(len(nums2)):\n for j in range(i+1, len(nums2)):\n v1 = nums2[i]\n v2 = nums2[j]\n fv = v1*v2\n if fv in ds1:\n ans += ds1[fv]\n for i in range(len(nums1)):\n for j in range(i+1, len(nums1)):\n v1 = nums1[i]\n v2 = nums1[j]\n fv = v1*v2\n if fv in ds2:\n ans += ds2[fv]\n \n return ans\n```
1
1
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Java Solution Using HashMap
java-solution-using-hashmap-by-jjy_yang-lrtr
Attention: Need to change type to Long\n\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n int re=0;\n Map<Long,Integer>
jjy_yang
NORMAL
2020-09-06T04:07:08.933471+00:00
2020-09-06T04:07:08.933515+00:00
65
false
Attention: Need to change type to Long\n```\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n int re=0;\n Map<Long,Integer> map=new HashMap<>();\n for(int i:nums1){\n long l=(long)i*(long)i;\n int count=map.getOrDefault(l,0);\n map.put(l,count+1);\n }\n for(int i=0;i<nums2.length;i++){\n for(int j=i+1;j<nums2.length;j++){\n long p=(long)nums2[i]*(long)nums2[j];\n if(map.getOrDefault(p,0)>0){\n re+=map.get(p);\n }\n }\n }\n Map<Long,Integer> map2=new HashMap<>();\n for(int i:nums2){\n long l=(long)i*(long)i;\n int count=map2.getOrDefault(l,0);\n map2.put(l,count+1);\n }\n for(int i=0;i<nums1.length;i++){\n for(int j=i+1;j<nums1.length;j++){\n long p=(long)nums1[i]*(long)nums1[j];\n if(map2.getOrDefault(p,0)>0){\n re+=map2.get(p);\n }\n }\n }\n return re;\n }\n}\n```
1
1
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
[C++] 30s. Faster than 100%
c-30s-faster-than-100-by-subbuffer-2mkh
Sort first, and then check whether the 3 numbers can exist accoriding to the condition. For this purpose, we can use a HashMap to expedite the search. Thus, in
SubBuffer
NORMAL
2020-09-06T04:05:13.729730+00:00
2020-09-06T06:52:19.933729+00:00
168
false
Sort first, and then check whether the 3 numbers can exist accoriding to the condition. For this purpose, we can use a HashMap to expedite the search. Thus, in the beginning, we insert the elements into the HashMap (in C++ ```unordered_map```) and then check for the obvious relationship of ```nums1[i]^2 = nums2[j] * nums2[k]``` . We can increment the count by using the HashMap counts to make it even faster for the cases such as ```nums1 = [1,1,1,1]``` and ```nums2 = [1,1]```.\n```\nclass Solution {\npublic:\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n sort(nums1.begin(),nums1.end());\n sort(nums2.begin(),nums2.end());\n long count = 0;\n unordered_map<int,int> mp1;\n unordered_map<int,int> mp2;\n long num;\n for (int i = 0;i<nums1.size();i++){\n mp1[nums1[i]]++;\n }\n for (int i = 0;i<nums2.size();i++){\n mp2[nums2[i]]++;\n }\n for (int i = 0;i<nums1.size();i++){\n if (i>0 && nums1[i]==nums1[i-1]){\n continue;\n }\n if (nums1[i]>nums2.back()){\n break;\n }\n if (nums1[i]<nums2[0]){\n continue;\n }\n num = (long)nums1[i]*nums1[i];\n for (int j = 0;j<nums2.size();j++){\n if (j>0 && nums2[j]==nums2[j-1]){\n continue;\n }\n if (num/nums2[j]<nums2[0])\n break;\n if (num%nums2[j]==0 && num/nums2[j]>=nums2[j] && mp2.find(num/nums2[j])!=mp2.end()){\n if (num/nums2[j]==nums2[j]){\n count += mp1[nums1[i]]*(long)(mp2[nums2[j]]*(mp2[nums2[j]]-1))/2;\n break;\n }else{\n count += mp1[nums1[i]]*(long)mp2[nums2[j]]*mp2[num/nums2[j]];\n }\n }\n }\n }\n // cout<<"--------------------"<<endl;\n for (int i = 0;i<nums2.size();i++){\n if (i>0 && nums2[i]==nums2[i-1]){\n continue;\n }\n if (nums2[i]>nums1.back()){\n break;\n }\n if (nums2[i]<nums1[0]){\n continue;\n }\n num = (long)nums2[i]*nums2[i];\n for (int j = 0;j<nums1.size();j++){\n if (j>0 && nums1[j]==nums1[j-1]){\n continue;\n }\n if (num/nums1[j]<nums1[0])\n break;\n if (num%nums1[j]==0 && num/nums1[j]>=nums1[j] && mp1.find(num/nums1[j])!=mp1.end()){\n if (num/nums1[j]==nums1[j]){\n count += mp2[nums2[i]]*(long)(mp1[nums1[j]]*(mp1[nums1[j]]-1))/2;\n break;\n }else{\n count += mp2[nums2[i]]*(long)mp1[nums1[j]]*mp1[num/nums1[j]];\n }\n }\n }\n }\n return count;\n }\n \n};
1
0
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Python, Hashmap
python-hashmap-by-yseeker-6plc
\nclass Solution(object):\n def numTriplets(self, nums1, nums2):\n\n cnt = 0\n a = collections.defaultdict(int)\n b = collections.defaul
yseeker
NORMAL
2020-09-06T04:03:58.069536+00:00
2020-09-06T04:03:58.069583+00:00
230
false
```\nclass Solution(object):\n def numTriplets(self, nums1, nums2):\n\n cnt = 0\n a = collections.defaultdict(int)\n b = collections.defaultdict(int)\n \n for num in nums1:\n a[num*num] += 1\n \n for num in nums2:\n b[num*num] += 1\n \n for j in range(len(nums2)):\n for k in range(j+ 1, len(nums2)):\n c = nums2[j]*nums2[k]\n if c in a: cnt += a[c] \n \n for j in range(len(nums1)):\n for k in range(j+1, len(nums1)):\n c = nums1[j]*nums1[k]\n if c in b: cnt += b[c] \n \n return cnt\n```
1
0
['Python']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
[Python3] frequency table
python3-frequency-table-by-ye15-lsvk
\n\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n cnt1, cnt2 = Counter(nums1), Counter(nums2)\n \n
ye15
NORMAL
2020-09-06T04:02:49.554518+00:00
2020-09-06T04:02:49.554579+00:00
205
false
\n```\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n cnt1, cnt2 = Counter(nums1), Counter(nums2)\n \n def fn(x, y, freq): \n """Return count of triplet of nums[i]**2 = nums[j]*nums[k]."""\n ans = 0\n for xx in x: \n xx *= xx\n ans += sum(freq[xx//yy] - (yy == xx//yy) for yy in y if not xx%yy and xx//yy in freq)\n return ans//2\n\n return fn(nums1, nums2, cnt2) + fn(nums2, nums1, cnt1)\n```
1
0
['Python3']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Straightforward O(N^2) Java Solution with 2 HashMaps
straightforward-on2-java-solution-with-2-h595
\n public int numTriplets(int[] nums1, int[] nums2) {\n //hashMap: product -> freq\n HashMap<Long, Integer> map1 = new HashMap<>();\n Ha
billtang123
NORMAL
2020-09-06T04:02:11.789400+00:00
2020-09-06T04:02:11.789450+00:00
162
false
```\n public int numTriplets(int[] nums1, int[] nums2) {\n //hashMap: product -> freq\n HashMap<Long, Integer> map1 = new HashMap<>();\n HashMap<Long, Integer> map2 = new HashMap<>();\n int n1 = nums1.length;\n int n2 = nums2.length;\n for(int i=0;i<n1; i++){\n for(int j=i+1; j<n1; j++){\n Long prod = (long)nums1[i]*nums1[j];\n map1.put(prod, map1.getOrDefault(prod, 0) + 1);\n }\n }\n for(int i=0;i<n2; i++){\n for(int j=i+1; j<n2; j++){\n Long prod = (long) nums2[i]*nums2[j];\n map2.put(prod, map2.getOrDefault(prod, 0) + 1);\n }\n }\n //get res\n int res=0;\n for(int num : nums1){\n Long sqr = (long)num*num;\n res += map2.getOrDefault(sqr, 0);\n } \n for(int num : nums2){\n Long sqr = (long)num*num;\n res += map1.getOrDefault(sqr, 0);\n }\n return res;\n }\n```
1
0
[]
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Hard Way to solve, but constraints are small
hard-way-to-solve-but-constraints-are-sm-sdoc
IntuitionНужно посчитать тройки, где квадрат одного элемента из одного массива равен произведению двух элементов из другого. Это условие проверяется по всем воз
bezzerli
NORMAL
2025-04-08T00:47:10.023237+00:00
2025-04-08T00:47:10.023237+00:00
2
false
### Intuition Нужно посчитать тройки, где квадрат одного элемента из одного массива равен произведению двух элементов из другого. Это условие проверяется по всем возможным парам. ### Approach 1. Посчитаем частоты квадратов всех элементов `nums1` и `nums2` (храним в словарях). 2. Для всех пар в `nums2`, проверим, есть ли их произведение среди квадратов `nums1` — это Type 1. 3. Для всех пар в `nums1`, проверим, есть ли их произведение среди квадратов `nums2` — это Type 2. 4. Сложим количество подходящих троек из обоих типов. ### Complexity - **Time complexity**: $$O(n_1^2 + n_2^2)$$, где \( n_1 \) и \( n_2 \) — длины массивов `nums1` и `nums2`. - **Space complexity**: $$O(n_1 + n_2)$$ — для хранения словарей с квадратами. # Code ```python3 [] class Solution: def numTriplets(self, nums1: list[int], nums2: list[int]) -> int: n1 = len(nums1) n2 = len(nums2) nums1_freq = {} nums2_freq = {} for i in range(n1): square = nums1[i] * nums1[i] if square in nums1_freq: nums1_freq[square] += 1 else: nums1_freq[square] = 1 for i in range(n2): square = nums2[i] * nums2[i] if square in nums2_freq: nums2_freq[square] += 1 else: nums2_freq[square] = 1 # print(nums1_freq, nums2_freq) ans = 0 for i in range(n1): for j in range(i + 1, n1): val = nums1[i] * nums1[j] if val in nums2_freq: ans += nums2_freq[val] for i in range(n2): for j in range(i + 1, n2): val = nums2[i] * nums2[j] if val in nums1_freq: ans += nums1_freq[val] return ans # print(Solution().numTriplets(nums1 = [7,7,8,3], nums2 = [1,2,9,7])) ```
0
0
['Array', 'Hash Table', 'Math', 'Python3']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
easy solution
easy-solution-by-owenwu4-q6wd
Intuitionprecompute squared freuencies using a hashmapApproachComplexity Time complexity: Space complexity: Code
owenwu4
NORMAL
2025-04-07T21:27:46.922644+00:00
2025-04-07T21:27:46.922644+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> precompute squared freuencies using a hashmap # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def numTriplets(self, nums1: List[int], nums2: List[int]) -> int: fd = defaultdict(int) for n in nums1: fd[n ** 2] += 1 sd = defaultdict(int) for n in nums2: sd[n ** 2] += 1 print(fd, sd) ans = 0 for i in range(len(nums2)): for j in range(i + 1, len(nums2)): if nums2[i] * nums2[j] in fd: ans += fd[nums2[i] * nums2[j]] for i in range(len(nums1)): for j in range(i + 1, len(nums1)): if nums1[i] * nums1[j] in sd: ans += sd[nums1[i] * nums1[j]] return ans ```
0
0
['Python3']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Python, Hashing, Brute Force
python-hashing-brute-force-by-mickeyhao-n5x6
Intuition & ApproachPrecalculate the square of numbers in both lists, and store the frequency. Then iterate through both lists to see if the product of nums2[j]
MickeyHao
NORMAL
2025-01-13T19:27:38.258977+00:00
2025-01-13T19:27:38.258977+00:00
12
false
# Intuition & Approach Precalculate the square of numbers in both lists, and store the frequency. Then iterate through both lists to see if the product of `nums2[j]*nums2[k]` is in the frequency table of `nums1`. Do the same to the other list. # Complexity - Time complexity: $O(N^2)$ - Space complexity: $O(N)$ # Code ```python3 [] class Solution: def numTriplets(self, nums1: List[int], nums2: List[int]) -> int: hash1 = defaultdict(lambda: 0) hash2 = defaultdict(lambda: 0) for num in nums1: hash1[num**2] += 1 for num in nums2: hash2[num**2] += 1 res = 0 for j in range(len(nums1)): for k in range(j+1, len(nums1)): res += hash2[nums1[j] * nums1[k]] for j in range(len(nums2)): for k in range(j+1, len(nums2)): res += hash1[nums2[j] * nums2[k]] return res ```
0
0
['Python3']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers
1577-number-of-ways-where-square-of-numb-cai4
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-13T16:52:31.716673+00:00
2025-01-13T16:52:31.716673+00:00
12
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int numTriplets(vector<int>& nums1, vector<int>& nums2) { int count = 0; unordered_map<long long, int> productMap1; unordered_map<long long, int> productMap2; // Type 1: nums1[i]^2 = nums2[j] * nums2[k] for (int j = 0; j < nums2.size(); ++j) { for (int k = j + 1; k < nums2.size(); ++k) { productMap1[(long long)nums2[j] * nums2[k]]++; } } for (int i = 0; i < nums1.size(); ++i) { long long target = (long long)nums1[i] * nums1[i]; if (productMap1.find(target) != productMap1.end()) { count += productMap1[target]; } } // Type 2: nums2[i]^2 = nums1[j] * nums1[k] for (int j = 0; j < nums1.size(); ++j) { for (int k = j + 1; k < nums1.size(); ++k) { productMap2[(long long)nums1[j] * nums1[k]]++; } } for (int i = 0; i < nums2.size(); ++i) { long long target = (long long)nums2[i] * nums2[i]; if (productMap2.find(target) != productMap2.end()) { count += productMap2[target]; } } return count; } }; ```
0
0
['C++']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Simple | Intuitive
simple-intuitive-by-richardleee-147y
IntuitionApproachComplexity Time complexity: Space complexity: Code
RichardLeee
NORMAL
2025-01-12T16:10:50.356357+00:00
2025-01-12T16:10:50.356357+00:00
11
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int numTriplets(int[] nums1, int[] nums2) { return count(nums1, nums2) + count(nums2, nums1); } public int count(int[] nums1, int[] nums2) { Map<Long, Integer> map = new HashMap<>(); int res = 0; for (int num : nums1) { long product = (long)num * num; map.put(product, map.getOrDefault(product, 0) + 1); } Map<Integer, Integer> map2 = new HashMap<>(); for (int num: nums2) { for (long product : map.keySet()) { if (product % num != 0) continue; int target = (int)(product / num); res += (map.get(product))* map2.getOrDefault(target, 0); } map2.put(num, map2.getOrDefault(num, 0) + 1); } return res; } } ```
0
0
['Java']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++ O(NM) Time, O(1) Auxiliary space, beat 95% runtime solution w/ Detailed explanation
c-onm-time-o1-auxiliary-space-beat-95-ru-hhz7
Intuition\nJust considering a single type (where nums1 is the "target" and nums2 is the "combinations" vector). We may make a few observations:\n\nObservations:
nicklai
NORMAL
2024-11-04T08:20:57.500917+00:00
2024-11-04T08:20:57.500949+00:00
16
false
# Intuition\nJust considering a single type (where nums1 is the "target" and nums2 is the "combinations" vector). We may make a few observations:\n\nObservations:\n- The values of the numbers are **non-negative**, limited to the range 1~100,000\n - If we deal with **sorted** nums1 and nums2, we can we can do some left-right pointer shenanigans as they traverse closer to some centre-point\n- There can be duplicates\n - We need to account for these possibilities\n - Possible runtime optimization here\n\n# Approach\nWith that in mind, intuitively, we want to approach some solution that iterates upon the "combinations" with two pointers that try to keep the product as close to the target as possible.\n\nFor example:\nnums1 = [1 1 3 **4** 6 8]\n("4" is our current "target")\nnums2 = [**1** 2 2 3 4 4 8 **12**]\n(leftInd is 0 and rightInd is 7)\n1 x 12 < 4 x 4\ntherefore increment leftInd to increase our product\n\n[1 1 3 **4** 6 8]\n[1 **2** 2 3 4 4 8 **12**]\n2 x 12 > 4 x 4\ntherefore decrement rightInd to decrease our product\n\n[1 1 3 **4** 6 8]\n[1 **2** 2 3 4 4 **8** 12]\n2 x 8 == 4 x 4\nfound possible product, process duplicates accordingly \n\netc...\n\nIn terms of finding the combinations, if there are no duplicates, the solution is trivial (you just increment count by 1)\n\nHowever, if there are duplicates, we need 2 ways of handling it:\n- If the leftNum (num2[leftInd]) is different from the rightNum\n - We find all combinations for our quantity of leftNums for every rightNum, which is simply a product of the two quantities\n- If the leftNum is the same as the rightNum (in other words, our leftNum == rightNum == target)\n - Then we need to find all possible combinations of any pair of these number\'s indices, which is a simple combinations operation (quantity Choose 2, or qC2)\n\nHere is the pseudocode implementation:\n- First, sort the nums1 and num2 vectors\n - We are assuming mutations are ok, this allows us to reduce additional space to O(1) for our function\n- Conduct our combination-counting process twice\n - swap nums1 and nums2 for type1 and type2 triplets\n - Traverse over nums1:\n - count duplicate nums1[i] values and assign to variable "multiplier"\n - compute our "target" value from the square of nums1[i]\n - note that we\'ll need to use long long here since unsigned int caps at 4 x 10^9\n - double-pointer traverse through nums2 with "j" and "k" being a leftInd and rightInd respectively\n - if product of nums2[leftInd] and nums2[rightInd] == target\n - count the number of duplicates on the left\n - count the number of duplicates on the right\n - if the left and right numbers are different, simply multiply together to find # of possible combunations\n - if the left and right numbers are the same, use find all possible combinations using nC2 where n = leftCount + rightCount\n - if the product is greater than the target\n - the rightInd value is too high, decrement rightInd\n - if the product is less than the target\n - the leftInd value is too low, increment leftInd\n- return our count at the end\n\n# Complexity\n- Time complexity:\n**O(nlog(n))** for sorting, where n is the max length between nums1 and nums2\n**O(nm)** for iterating over nums1 while looking for possible products in nums2\n**O(1)** for computing combinations (since any number\'s value is restricted to 1~10^5)\nTotal complexity = O(2 * (nlog(n) + O(nm) * O(1)))\n\u2248 **O(nm)**\n\n- Space complexity:\n**NOTE:** We don\'t auxillary space that scales with the input, making this an extremely space-efficient solution.\n**O(n + m)** for nums1 and nums2 vectors\n**O(1)** for all other local variables that we store\nAuxillary space = **O(1)**\nTotal space = **O(n + m)**\n\n# Code\n```cpp []\n// helper function to compute combinations of nCk O(N)\ntemplate <typename T>\nT combinations(T n, T k) {\n if (k > n) return 0; // If k is greater than n, there are no valid combinations\n if (k == 0 || k == n) return 1; // Base cases: nC0 = nCn = 1\n\n T result = 1;\n for (T i = 1; i <= k; ++i) {\n result *= n - i + 1;\n result /= i;\n }\n return result;\n}\n\nclass Solution {\npublic:\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n // sort our nums1/2 vectors\n std::sort(nums1.begin(), nums1.end()); // >> O(nlog(n)) where "n" is length of nums1\n std::sort(nums2.begin(), nums2.end()); // >> O(nlog(n)) where "m" is length of nums2\n\n // iterate and perform count twice\n unsigned int count = 0;\n for (int rep = 0; rep < 2; rep++) {\n // iterate over targets\n unsigned short int i = 0;\n while (i < nums1.size()) { // O(n+m)\n unsigned short int multiplier = 1;\n // if the current integer is the same as the next one, increment multiplier\n while (i + 1 < nums1.size() && nums1[i] == nums1[i + 1]) {\n multiplier++;\n i++;\n }\n\n // iterate through other vector, checking multiple\n unsigned short int leftInd = 0;\n unsigned short int rightInd = nums2.size() - 1;\n unsigned long long target = static_cast<unsigned long long>(nums1[i]) \n * static_cast<unsigned long long>(nums1[i]);\n while (leftInd < rightInd) {\n unsigned long long product = static_cast<unsigned long long>(nums2[leftInd]) \n * static_cast<unsigned long long>(nums2[rightInd]);\n if (product == target) {\n // product same as target\n bool leftRightSame = nums2[leftInd] == nums2[rightInd];\n\n // count number of duplicates on "right side" of our multiplication\n unsigned short int rightSameCount = 1;\n while (rightInd - 1 > leftInd\n && nums2[rightInd] == nums2[rightInd - 1]) {\n rightSameCount++;\n rightInd--;\n }\n \n // count number of duplicates on "left side" of our multiplication\n unsigned short int leftSameCount = 1;\n while (leftInd + 1 < rightInd\n && nums2[leftInd] == nums2[leftInd + 1]) {\n leftSameCount++;\n leftInd++;\n }\n\n // find all possible combinations\n if (leftRightSame) {\n // use mathematical combination function\n count += multiplier * combinations(leftSameCount + rightSameCount, 2);\n } else {\n // use simple product to find all combinations \n count += multiplier * leftSameCount * rightSameCount;\n }\n\n // decrement right index by default, since that is traversed first\n rightInd--;\n } else if (product > target) {\n // product greater than target, move rightInd left\n rightInd--;\n } else {\n // product less than target, move leftInd right\n leftInd++;\n }\n }\n i++;\n }\n\n // swap nums1 and nums2 and repeat process\n std::swap(nums1, nums2);\n }\n\n return count;\n }\n};\n```
0
0
['C++']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Very intuitive solution using dictionary
very-intuitive-solution-using-dictionary-xpd2
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
belka
NORMAL
2024-10-28T19:39:32.897017+00:00
2024-10-28T19:39:32.897041+00:00
10
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# Code\n```python3 []\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n d1,d2=defaultdict(int),defaultdict(int)\n for num in nums1:\n d1[num*num]+=1\n for num in nums2:\n d2[num*num]+=1\n res=0\n for i in range(len(nums1)):\n for j in range(i+1,len(nums1)):\n tmp=nums1[i]*nums1[j]\n if tmp in d2: res+=d2[tmp]\n \n for i in range(len(nums2)):\n for j in range(i+1,len(nums2)):\n tmp=nums2[i]*nums2[j]\n if tmp in d1: res+=d1[tmp]\n return res\n```
0
0
['Python3']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Easy simple code || Beats 90|| O(M*N)|| O(M+N)
easy-simple-code-beats-90-omn-omn-by-sum-s1t6
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
sumanth2328
NORMAL
2024-10-15T04:16:15.661749+00:00
2024-10-15T04:16:15.661780+00:00
24
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# Code\n```python3 []\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n dic1=Counter(nums1)\n dic2=Counter(nums2)\n def check(nums1,dic):\n count=0\n for i in range(len(nums1)):\n tempdic = dict(dic)\n for j in tempdic:\n temp=nums1[i] ** 2 // j\n if temp*j==nums1[i]**2 and temp in tempdic:\n if temp==nums1[i] and tempdic[j]==1:\n continue\n if temp==j and tempdic[temp]>1:\n count+=(tempdic[temp]*(tempdic[temp]-1))//2\n elif tempdic[temp]>0 and tempdic[j]>0:\n count+=tempdic[temp]*tempdic[j]\n tempdic[j]=0\n print(nums1[i],j,temp)\n\n return count\n x=check(nums1,dic2)\n y=check(nums2,dic1)\n return x+y\n```
0
0
['Array', 'Hash Table', 'Math', 'Counting', 'Python3']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++ Solution || Using Maps
c-solution-using-maps-by-vaibhav_arya007-8ba1
Code\ncpp []\nclass Solution {\n // Function to count the number of valid triplets where square of a number from `A`\n // is equal to the product of two n
Vaibhav_Arya007
NORMAL
2024-10-03T22:04:54.421323+00:00
2024-10-03T22:04:54.421347+00:00
24
false
# Code\n```cpp []\nclass Solution {\n // Function to count the number of valid triplets where square of a number from `A`\n // is equal to the product of two numbers from `B`\n int count(vector<int> &A, vector<int> &B) {\n int ans = 0;\n unordered_map<int, int> freqMap;\n\n // Build a frequency map for elements in array `B`\n for (int num : B) {\n freqMap[num]++;\n }\n\n // For each element `a` in `A`, check if its square can be written\n // as the product of two numbers from `B`\n for (int a : A) {\n long target = (long)a * a; // Square of `a` (use long to prevent overflow)\n \n // Check for each number `b` in `B` (using the frequency map)\n for (auto &[b, count] : freqMap) {\n // If the target is not divisible by `b`, skip this iteration\n if (target % b != 0) continue;\n \n // Calculate the other factor needed to get the product as the target\n int otherFactor = target / b;\n\n // If `otherFactor` exists in the map\n if (freqMap.count(otherFactor)) {\n // If `b` and `otherFactor` are the same, count the valid pairs (combination)\n if (b == otherFactor) {\n // Choose 2 from `count` occurrences of `b` (because b*b = target)\n ans += count * (count - 1);\n } else {\n // If `b` and `otherFactor` are different, count the valid pairs\n ans += count * freqMap[otherFactor];\n }\n }\n }\n }\n \n // Each valid pair is counted twice, so divide the result by 2\n return ans / 2;\n }\n\npublic:\n // Main function to find the total number of valid triplets\n int numTriplets(vector<int>& A, vector<int>& B) {\n // Count triplets for both `A` -> `B` and `B` -> `A`\n return count(A, B) + count(B, A);\n }\n};\n\n```
0
0
['C++']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++ Solution || Brute Force
c-solution-brute-force-by-vaibhav_arya00-usht
Code\ncpp []\nclass Solution {\npublic:\n // Update the function to use long long for calculations\n int solve(vector<int>& nums1, vector<int>& nums2) {\n
Vaibhav_Arya007
NORMAL
2024-10-03T21:56:06.753612+00:00
2024-10-03T21:56:06.753655+00:00
4
false
# Code\n```cpp []\nclass Solution {\npublic:\n // Update the function to use long long for calculations\n int solve(vector<int>& nums1, vector<int>& nums2) {\n int count = 0;\n\n for (int i = 0; i < nums1.size(); i++) {\n long long target = (long long)nums1[i] * nums1[i]; // Square of nums1[i]\n\n for (int j = 0; j < nums2.size(); j++) {\n for (int k = j + 1; k < nums2.size(); k++) {\n if (target == (long long)nums2[j] * nums2[k]) { // Compare using long long\n count++;\n }\n }\n }\n }\n\n return count;\n }\n\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n return solve(nums1, nums2) + solve(nums2, nums1);\n }\n};\n\n```
0
0
['C++']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Hashing || Super Simple || C++
hashing-super-simple-c-by-lotus18-ppmx
Code\n\nclass Solution \n{\npublic:\n int numTriplets(vector<int>& nums1, vector<int>& nums2) \n {\n map<long long,int> m1, m2;\n for(auto n
lotus18
NORMAL
2024-08-18T17:41:20.534244+00:00
2024-08-18T17:41:20.534296+00:00
20
false
# Code\n```\nclass Solution \n{\npublic:\n int numTriplets(vector<int>& nums1, vector<int>& nums2) \n {\n map<long long,int> m1, m2;\n for(auto n: nums1) m1[(long long)n*n]++;\n for(auto n: nums2) m2[(long long)n*n]++;\n int ans=0;\n for(int x=0; x<nums2.size(); x++)\n {\n for(int y=x+1; y<nums2.size(); y++)\n {\n ans+=m1[(long long)nums2[x]*nums2[y]];\n }\n }\n for(int x=0; x<nums1.size(); x++)\n {\n for(int y=x+1; y<nums1.size(); y++)\n {\n ans+=m2[(long long)nums1[x]*nums1[y]];\n }\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Simple and Easy JAVA Solution using HashMap
simple-and-easy-java-solution-using-hash-jwoj
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
Triyaambak
NORMAL
2024-07-29T18:02:41.906735+00:00
2024-07-29T18:02:41.906788+00:00
26
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# Code\n```\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n int res = 0;\n res += solve(nums1,nums2);\n res += solve(nums2,nums1);\n return res;\n }\n\n private int solve(int nums1[] , int nums2[]){\n int n = nums1.length;\n int m = nums2.length;\n int res = 0;\n Map<Long,Integer> map = new HashMap<>();\n\n for(int i=0;i<n;i++){\n long sqr = (long)nums1[i] * (long)nums1[i];\n map.put(sqr,map.getOrDefault(sqr,0)+1);\n }\n\n for(int j=0;j<m-1;j++){\n for(int k=j+1;k<m;k++){\n long prod = (long)nums2[j] * (long)nums2[k];\n if(map.containsKey(prod))\n res+=map.get(prod);\n }\n }\n \n return res;\n }\n}\n```
0
0
['Java']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
✅ C++ Solution in O(mn) complexity clearly explained with comments
c-solution-in-omn-complexity-clearly-exp-1303
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
rohith_nair_2021
NORMAL
2024-07-15T19:12:19.482418+00:00
2024-07-15T19:12:19.482439+00:00
27
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: ```O(mn)```\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: ```O(n) or O(m) depending on which is larger```\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int getTriplets(vector<int>& nums1, vector<int>& nums2) {\n int sum = 0;\n\n // Storing the count of each element in the array of which we\'re calculating the squares of\n unordered_map<int, int> num_map;\n for(auto i:nums1) num_map[i]++;\n\n // Now, traversing through the second array\n for(int i = 0; i < nums2.size(); i++) {\n for(int j = i+1; j < nums2.size(); j++) {\n\n // This should be the square of one of the numbers in the other array\n long long product = (long)nums2[i] * nums2[j];\n\n // If the product can have a perfect square root\n if(ceil(sqrt(product)) == floor(sqrt(product))) {\n\n // This is going to be our target that we should try finding in the other array\n // And we\'ll use the map for it. If it\'s found, we\'ll add it\'s total occurence to the total sum\n long long int target = sqrt(product);\n if(num_map.find(target) != num_map.end()) sum += num_map[target];\n }\n }\n }\n\n // returning the sum\n return sum;\n }\n\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n return getTriplets(nums1, nums2) + getTriplets(nums2, nums1);\n }\n};\n```
0
0
['Array', 'Hash Table', 'C++']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Clean Python Solution, TC : O(n*m) , SC : O(n+m)
clean-python-solution-tc-onm-sc-onm-by-a-qu8f
Approach\n Describe your approach to solving the problem. \n1. We need to take every squares of nums1 and find product pairs in nums2 and viceversa.\n\n2. So we
AGHIL_P
NORMAL
2024-07-03T17:44:47.259616+00:00
2024-07-03T17:44:47.259659+00:00
48
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We need to take every squares of nums1 and find product pairs in nums2 and viceversa.\n\n2. So we can take the count of squares in both array to minimise repititive work, like if there are same numbers mutiple times. And save the squares and their count in hashmap sq1 and sq2\n\n3. After that we can take every square from sq1 and find pairs in nums2. The approach came to my mind to minimise this task is the TWO SUM problem ( 1st problem on leetcode ). \n\n4. so if we take one number \'n\' and save the another required number in a hashmap and if that come after, we increment the result variable by number of time it\'s pair occured before multiply by the number of squares present in nums1 ie, sq1[n*n].\n\n5. Then we repeat the task for type 2.\n\n6. Finally returns the result.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n*m)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n+m)$$\n# Code\n```\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n sq1=defaultdict(int)\n sq2=defaultdict(int)\n res=0\n\n #saving the count pf squares\n\n for n in nums1:\n sq1[n*n]+=1\n for n in nums2:\n sq2[n*n]+=1\n\n #type 1\n\n for s in sq1:\n h2=defaultdict(int)\n for n in nums2:\n rem=s%n\n if not rem:\n res+=h2[n]*sq1[s]\n h2[s//n]+=1\n\n #type 2\n\n for s in sq2:\n h1=defaultdict(int)\n for n in nums1:\n rem=s%n\n if not rem:\n res+=h1[n]*sq2[s]\n h1[s//n]+=1\n\n return res\n```
0
0
['Hash Table', 'Counting', 'Python3']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
O(N2) complexity
on2-complexity-by-sirispandana77-hppb
Intuition\n Describe your first thoughts on how to solve this problem. \nIf the target value is a multiple of the element in the list, then the % will be 0. To
sirispandana77
NORMAL
2024-07-01T18:37:13.303930+00:00
2024-07-01T18:37:13.303956+00:00
10
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf the target value is a multiple of the element in the list, then the % will be 0. To avaoid mulitple calculation a dict can be used to store the values.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo calculate the pairs, lets have a list and a target. we iterate over the list and check if the element is a factor of the target and if so, before incrementing the count, lets check a dict if there\'s a complementing factor for this element so that factor 1 * factor 2 = target. If there is, add the count of that factor to the total value. While we iterate over the list, we keep count of the factors so that they might become the factor 1\'s for some other elements we are yet to iterate over. \n# Complexity\n- Time complexity: O(N2)\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:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n from collections import defaultdict\n nums1.sort()\n nums2.sort()\n def findtarget(l,t):\n c=0\n d=defaultdict(int)\n #l.sort()\n #print("l, target", l,t)\n for i in l:\n if t%i==0:\n c+=d[int(t/i)]\n d[i]+=1\n #print("c: ",c)\n return c\n def common(l,l1):\n #print("l,l1", l,l1)\n c=0\n d=defaultdict(int)\n for i in l:\n # print("i,l", i,l, d)\n if d[i*i]>0:\n c+=d[i*i]\n else:\n x=findtarget(l1,i*i)\n d[i*i]+=x\n c+=x\n # print("### returning c",c)\n return c\n total=common(nums1,nums2)+common(nums2,nums1)\n return total\n```
0
0
['Python3']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Easy Two Maps Approach
easy-two-maps-approach-by-aman_91-d6ny
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
aman_91
NORMAL
2024-05-20T10:03:19.686405+00:00
2024-05-20T10:03:19.686432+00:00
31
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# Code\n```\nclass Solution {\npublic:\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n int n=nums1.size();\n int m=nums2.size(); \n unordered_map<long long,long long>mp1;\n unordered_map<long long,long long>mp2;\n for(int i=0;i<n-1;i++){\n for(int j=i+1;j<n;j++){\n long long mul=(long)((long)nums1[i]*(long)nums1[j]);\n mp1[mul]++;\n }\n }\n for(int i=0;i<m-1;i++){\n for(int j=i+1;j<m;j++){\n mp2[(long)((long)nums2[i]*(long)nums2[j])]++;\n }\n }\n long long cnt=0;\n for(int i=0;i<m;i++){\n if(mp1.find((long)nums2[i]*(long)nums2[i])!=mp1.end()){\n cnt+=mp1[(long)nums2[i]*(long)nums2[i]];\n }\n }\n for(int i=0;i<n;i++){\n if(mp2.find((long)nums1[i]*(long)nums1[i])!=mp2.end()){\n cnt+=mp2[((long)nums1[i]*(long)nums1[i])];\n }\n }\n return (int)cnt;\n\n\n }\n};\n```
0
0
['C++']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Solution Number of Ways Where Square of Number Is Equal to Product of Two Numbers
solution-number-of-ways-where-square-of-5c5yu
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
Suyono-Sukorame
NORMAL
2024-05-18T09:42:03.244072+00:00
2024-05-18T09:42:03.244101+00:00
0
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# Code\n```\nclass Solution {\n public function numTriplets($nums1, $nums2) {\n $mp1 = [];\n $mp2 = [];\n\n for ($i = 0; $i < count($nums1); $i++) {\n for ($j = $i + 1; $j < count($nums1); $j++) {\n $product = (int)$nums1[$i] * (int)$nums1[$j];\n if (!isset($mp1[$product])) {\n $mp1[$product] = 0;\n }\n $mp1[$product]++;\n }\n }\n\n for ($i = 0; $i < count($nums2); $i++) {\n for ($j = $i + 1; $j < count($nums2); $j++) {\n $product = (int)$nums2[$i] * (int)$nums2[$j];\n if (!isset($mp2[$product])) {\n $mp2[$product] = 0;\n }\n $mp2[$product]++;\n }\n }\n\n $count = 0;\n\n foreach ($nums1 as $num) {\n $square = (int)$num * (int)$num;\n if (isset($mp2[$square])) {\n $count += $mp2[$square];\n }\n }\n\n foreach ($nums2 as $num) {\n $square = (int)$num * (int)$num;\n if (isset($mp1[$square])) {\n $count += $mp1[$square];\n }\n }\n\n return $count;\n }\n}\n\n```
0
0
['PHP']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Short & Simple. O(n^2 + m^2)
short-simple-on2-m2-by-3s_akb-dzzg
\npublic class Solution {\n\n int c(int[] a, int[] b)\n {\n int res = 0;\n var aa = a.Select(x => (long)x * (long)x).GroupBy(x => x).ToDicti
3S_AKB
NORMAL
2024-05-07T15:29:09.710580+00:00
2024-05-07T15:29:09.710600+00:00
3
false
\npublic class Solution {\n\n int c(int[] a, int[] b)\n {\n int res = 0;\n var aa = a.Select(x => (long)x * (long)x).GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());\n for (int i = 0; i < b.Length; i++)\n for (int k = i + 1; k < b.Length; k++)\n if (aa.ContainsKey((long)b[i] * b[k]))\n res += aa[(long)b[i] * b[k]];\n return res;\n }\n\n public int NumTriplets(int[] nums1, int[] nums2) {\n return c(nums1, nums2) + c(nums2, nums1);\n }\n}\n```
0
0
['C#']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Java Solution with HashMap and binary search
java-solution-with-hashmap-and-binary-se-h2iu
Intuition\nCounting, HashMap and binary search\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity:\n Add your ti
jhapranay
NORMAL
2024-04-30T19:24:29.044549+00:00
2024-04-30T19:24:29.044579+00:00
20
false
# Intuition\nCounting, HashMap and binary search\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# Code\n```\nclass Solution {\n\n public int numTriplets(int[] nums1, int[] nums2) {\n Map<Integer, List<Integer>> valIndexHolder = getMap(nums2);\n int ans = 0;\n\n for (int num : nums1) {\n long n = (long)num * num;\n ans += getCount(valIndexHolder, n);\n }\n valIndexHolder = getMap(nums1);\n\n for (int num : nums2) {\n long n = (long)num * num;\n ans += getCount(valIndexHolder, n);\n }\n return ans;\n }\n\n private int getCount(Map<Integer, List<Integer>> valIndexHolder, long sqNum) {\n int ans = 0;\n\n for (int val : valIndexHolder.keySet()) {\n\n if (sqNum % val != 0) {\n continue;\n }\n int result = (int)(sqNum / val);\n List<Integer> resultList = valIndexHolder.getOrDefault(result, new ArrayList<>());\n\n if (result == val) {\n\n if (resultList.size() > 1) {\n ans += resultList.size() * (resultList.size() - 1) / 2;\n }\n } else {\n List<Integer> valList = valIndexHolder.get(val);\n int i = 0;\n\n for (; i < valList.size(); i++) {\n int index = binarySearchGreaterThan(resultList, valList.get(i));\n\n if (index != -1) {\n ans += resultList.size() - index;\n }\n }\n }\n }\n return ans;\n }\n\n private int binarySearchGreaterThan(List<Integer> resultList, int index) {\n int lo = 0;\n int hi = resultList.size() - 1;\n int ans = -1;\n\n while (lo <= hi) {\n int pivot = lo + (hi - lo) / 2;\n\n if (resultList.get(pivot) < index) {\n lo = pivot + 1;\n } else {\n hi = pivot - 1;\n ans = pivot;\n }\n }\n return ans;\n }\n\n private Map<Integer, List<Integer>> getMap(int[] nums) {\n Map<Integer, List<Integer>> valIndexHolder = new HashMap<>();\n\n for (int i = 0; i < nums.length; i++) {\n List<Integer> list = valIndexHolder.getOrDefault(nums[i], new ArrayList<>());\n list.add(i);\n valIndexHolder.put(nums[i], list);\n }\n return valIndexHolder;\n }\n}\n```
0
0
['Hash Table', 'Binary Search', 'Counting', 'Java']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Python 3: FT 100%, LMT 90%: TC O(N1 log(N1) + N2 log(N2) + S1 + S2): Count and Sort Uniques
python-3-ft-100-lmt-90-tc-on1-logn1-n2-l-oy0z
Intuition\n\nWelcome to my ~6th FT 100% algorithm!\n\nAnd asymptotically it could be even faster on large inputs, see below about iterating over divisors and th
biggestchungus
NORMAL
2024-03-23T21:33:25.248135+00:00
2024-03-23T21:33:25.248151+00:00
30
false
# Intuition\n\nWelcome to my ~6th FT 100% algorithm!\n\nAnd asymptotically it could be even faster on large inputs, see below about iterating over divisors and the excellent average case complexity.\n\nSuper brute force is to do a three-pointer algorithm, checking all triplets and counting up the number of matches. But we don\'t have time for that; `1000^3` is `1e9` which will give TLE. (LC usually allows for order ~1e7 ops at the most).\n\nFortunately we can see from the input that the only restriction on `i, j, k` besides the values is that `j < k`. The product of two numbers doesn\'t depend on their order - multiplication commutes. So really the restriction is\n* for `nums[j] != nums[k]: j != k`\n* for `nums[j] == nums[k]: count(nums[k]) choose 2`\n\n## Combinatorics\n\nOnce we realize order doesn\'t matter, we realize that when `vi**2 == vj * vk` and `vj != vk`, then the count is\n* the count of `vi`\n* times the count of `vj`\n* times the count of `vk`\n\nBecause every copy of `vj` can be multiplied with any copy of `vk` to get `vi**2`, and we\'ll know they have different indices.\n\nIf `vj == vk`, then we can\'t do `count[vj]*count[vj]` because that will include pairs where `k==j` and also where we count both `j < k` and `j > k`. Fortunately we can solve that with combinatorics: we know every distinct *pair* of indices will give us an answer. So it\'s `count[vj] choose 2` for the `j < k` pairs.\n\n## Efficient Iteration\n\nWe could check every single triple in `O(N1 * N2)` time, the product of array sizes.\n\nWe can do better in the worst case though. Instead, get the unique values in each array and sort.\n\nThen to form `nums1[i]**2`, we need `nums2[j]*nums2[k]` to be the same. Since we determined earlier the answer only needs us to get counts, let\'s say `nums2[j]` is the smaller number.\n\nThen we only need to iterate over the unique values in `nums2` that are at most `nums1`.\n\n# Approach\n\nThe `nums1[i]**2 = ...` and `nums2[i]**2 = ...` are mirror images of each other.\n\nSo I wrote a helper function that takes "left" and "right" counts and uniques to get the answer. Then I called it with `left` referring to `nums1`, then again with `left` referring to `nums2`.\n\n# Complexity\n- Time complexity: `O(N1 log(N1) + N2 log(N2) + S1 + S2)`\n - `N1, N2` are the lengths of the arrays\n - `S1, S2` are the sums of the arrays\n - the `N log(N)` terms come from sorting the unique factors\n - the sum terms come from the loop. For each value `vi` in `nums2`, we check all numbers in `nums2` up to `vi`. That\'s `O(vi)` worst case, if nums2 has *all* of `1..vi`. Summed across all `O(N)` uniques, that\'s asymptotically `O(S)` where `S` is the sum\n\n- Space complexity: `O(N1 + N2)`\n\nSo as is sometimes common, ye olde normal comparison sorting is the slowest part of the algorithm.\n\n# Possible Optimization: Iterate over Divisors\n\nIn `sqrt(max)` time we can get all prime divisors.\n\nSketch of why that works\n1. all numbers are the product of primes `2, 3, ..`, just one for prime numbers and obviously 2+ for composite numbers\n1. any composite number `n`, if it has a prime factor larger than `sqrt(n)`, only has one such factor. Proof: suppose it had two, `p1` and `p2`. Then `p1*p2 > sqrt(n)^2 == n`. Which is obviously not possible. So it can\'t have 2+\n\nSo that implies the following algorithm:\n* start with `n`\n* trial divide by all primes at most `sqrt(n)` until the remainder is 1\n* if the remainder after all the divisions is not 1, then it\'s that single prime factor greater than sqrt(n)\n\nAnyway, then we could iterate over just the divisors of each number by\n* first getting the prime factors\n* then using BFS to iterate over them\n\n## Worst Case for Iterating\n\nIn this way we\'d iterate over all factors of `n**2`, which turns out to be `O(e^(log(n)/log(log(n))))`. `log(log(n))` grows very slowly so it\'s not a big deal, but it is technically an asymptotic improvement.\n\nMoreover, most numbers that aren\'t e.g. 360 have few factors. For example, if the prime factors are `7` and `11`, then divisors are separated by gaps of `7`. As a further limit, we wouldn\'t be iterating over all powers of `7` - just up to the number of factors of `7` that `n` has... which is just `O(log(n))` of them at most.\n\nWith this optimization, the complexity of iterating over all possible divisors of `vi` would be reduced from `O(vi)` (guess and check all)` to `O(exp(log(vi)/log(log(vi))))`. Neat.\n\n## Typical Case For Iterating\n\nThat complexity is the absolute worst case though. There are a few numbers that have a *huge* number of prime factors, those that look like `p1**k1 * p2**k2` for small `p1` and p2`.\n\nFor most numbers though there are *many* fewer factors. In fact, the sum of the number of proper divisors for `1..n` only scales as `O(n log(n))`. **So on average, a number `n` only has `log(n)` divisors.**\n\nTherefore the typical time complexity with this algorithm would be\n* iterate over each number `vi`\n* look for the average `O(log(n))` divisors in the other list instead of all `O(vi)` numbers\n* so the complexity would drop from the sum of unique values to the sum of *logarithms* of the unique values\n\nThis is a huge savings!\n\n# Code\n```\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n # return number of t1 and t2 triplets\n\n # t1: nums1[i] = nums2[j]*nums2[k] for j < k\n # t2: nums2[i] = 1 1 \n\n # all numbers positive\n # order doesn\'t matter so sorting would probably help\n\n # for nums1[i] = 125, we could use a two-pointer for nj*nk... but not contig. so it would be O(N^2)\n\n # better: get counts of each element in nums1 and nums2\n # for v1, f1 in nums1 counts:\n # iterate over vj in nums2 < sqrt(v1), if divis then get vk and there are v1*vj*vk\n # then try sqrt(v1) itself if it\'s a perfect square, it would be f2*(f2-1) // 2 (f2 choose 2)\n\n # that costs O(n1*n2*sqrt(max))\n\n # faster?\n\n c1 = Counter(nums1)\n c2 = Counter(nums2)\n\n vs1 = list(c1.keys())\n vs2 = list(c2.keys())\n vs1.sort()\n vs2.sort()\n\n def count(left, lvals, right, rvals):\n ans = 0\n\n for vi, fi in left.items():\n for vj in rvals:\n if vj >= vi: break\n if vi**2 % vj == 0:\n fj = right[vj]\n fk = right.get(vi**2//vj, 0)\n ans += fi*fj*fk\n \n if vj == vi:\n fj = right[vj]\n ans += fi*(fj*(fj-1))//2\n\n return ans\n\n return count(c1, vs1, c2, vs2) + count(c2, vs2, c1, vs1)\n\n # TC O(N1 log(N1) + N2 log(N2) + (N1+N2)*sqrt(max))\n```
0
0
['Python3']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Python (Simple Hashmap)
python-simple-hashmap-by-rnotappl-zm56
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
rnotappl
NORMAL
2024-03-15T10:49:44.100186+00:00
2024-03-15T10:49:44.100209+00:00
33
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# Code\n```\nclass Solution:\n def numTriplets(self, nums1, nums2):\n def dfs(A,B):\n n, dict1, total = len(A), defaultdict(int), 0\n\n for i in B:\n dict1[i*i] += 1 \n\n for i in range(len(A)):\n for j in range(i+1,len(A)):\n total += dict1[A[i]*A[j]]\n\n return total \n\n return dfs(nums1,nums2) + dfs(nums2,nums1) \n```
0
0
['Python3']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
C++ || Similar to two sum problem with hash map
c-similar-to-two-sum-problem-with-hash-m-97fq
\n\n# Code\n\nclass Solution {\npublic:\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n std::unordered_map<int, int> m1, m2;\n\n
Gismet
NORMAL
2024-03-04T08:41:56.252004+00:00
2024-03-04T08:41:56.252037+00:00
28
false
\n\n# Code\n```\nclass Solution {\npublic:\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n std::unordered_map<int, int> m1, m2;\n\n for(int i : nums1)\n m1[i]++;\n \n for(int i : nums2)\n m2[i]++;\n\n int ans = 0;\n for(const auto& [k1, v1] : m1)\n {\n long long x = (long long)k1 * k1;\n int cnt = 0;\n for(const auto& [k2, v2] : m2)\n {\n if(x % k2 == 0 && m2.count(x / k2))\n {\n int y = m2[x / k2];\n if(k2 == x / k2)\n {\n ans +=v1 * ((y * (y - 1)) / 2);\n } else \n {\n cnt +=v1 * v2 * y;\n }\n }\n }\n cnt /= 2;\n ans += cnt;\n }\n\n\n for(const auto& [k1, v1] : m2)\n {\n long long x = (long long)k1 * k1;\n int cnt = 0;\n for(const auto& [k2, v2] : m1)\n {\n if(x % k2 == 0 && m1.count(x / k2))\n {\n int y = m1[x / k2];\n if(k2 == x / k2)\n {\n ans += v1 * ((y * (y - 1)) / 2);\n } else \n {\n cnt +=v1 * v2 * y;\n }\n }\n }\n cnt /= 2;\n ans += cnt;\n }\n\n\n return ans;\n }\n};\n```
0
0
['C++']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Easy solution Using two Hashmaps.
easy-solution-using-two-hashmaps-by-abhi-8uex
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1. Create two hashmaps
abhishek_biyani08
NORMAL
2024-02-26T14:59:40.620685+00:00
2024-02-26T14:59:40.620721+00:00
23
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create two hashmaps to store the products of each pair of numbers in each array.\n2. Add the products in the hashmaps respectively.\n3. Using for loop check if the square of a number from nums1 is already present in the hashmap where it has the products of pairs of numbers from nums2. Increment the count variable if the hashmap result is greater than 0.\n4. Repeat the same with nums2 also.\n5. Return the count at the end.\n\n# Complexity\n- Time complexity:\n$$O(n^2)+O(m^2)$$\n\n- Space complexity:\n$$O(n)+O(m)$$\n\n# Code\n```\nclass Solution {\npublic:\n int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n unordered_map<long long int, int> mp1;\n unordered_map<long long int, int> mp2;\n\n // Calculate the product of each pair in nums1 and store in mp1\n for (int i = 0; i < nums1.size(); i++) \n {\n for (int j = i + 1; j < nums1.size(); j++) \n {\n mp1[(long long)nums1[i] * nums1[j]]++;\n }\n }\n // Calculate the product of each pair in nums2 and store in mp2\n for (int i = 0; i < nums2.size(); i++) \n {\n for (int j = i + 1; j < nums2.size(); j++) \n {\n mp2[(long long)nums2[i] * nums2[j]]++;\n }\n }\n int count = 0;\n // Check if the product of numbers in nums2 is equal to square in nums1\n for (int i = 0; i < nums1.size(); i++) \n {\n int x = mp2[(long long)nums1[i] * nums1[i]];\n if (x > 0)\n count += x;\n }\n // Check if the product of numbers in nums1 is equal to square in nums2\n for (int i = 0; i < nums2.size(); i++) \n {\n int x = mp1[(long long)nums2[i] * nums2[i]];\n if (x > 0)\n count += x;\n }\n return count;\n }\n};\n```
0
0
['C++']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
JS || Solution by Bharadwaj
js-solution-by-bharadwaj-by-manu-bharadw-gynl
Code\n\nvar numTriplets = function (nums1, nums2) {\n return Triplets(nums1, nums2) + Triplets(nums2, nums1);\n\n function Triplets(nums1, nums2) {\n
Manu-Bharadwaj-BN
NORMAL
2024-02-01T07:24:15.244179+00:00
2024-02-01T07:24:15.244210+00:00
16
false
# Code\n```\nvar numTriplets = function (nums1, nums2) {\n return Triplets(nums1, nums2) + Triplets(nums2, nums1);\n\n function Triplets(nums1, nums2) {\n let res = 0;\n for (let i = 0; i < nums1.length; i++) {\n let target = nums1[i] * nums1[i], map = new Map();\n for (let j = 0; j < nums2.length; j++) {\n res += map.get(target / nums2[j]) || 0;\n map.set(nums2[j], (map.get(nums2[j]) || 0) + 1);\n }\n }\n return res;\n }\n};\n```
0
0
['JavaScript']
1
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Java simple hashmap solution
java-simple-hashmap-solution-by-dsa_geek-4alj
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \ncreated a check functio
dsa_geek
NORMAL
2024-01-01T05:52:58.853158+00:00
2024-01-01T05:52:58.853206+00:00
34
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ncreated a check function which checks the condition given in the question. and this check function is called twice as asked in question.\n\n# Code\n```\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n if(nums1.length<=1 || nums2.length<=1) return 0;\n return check(nums1,nums2)+ check(nums2,nums1);\n }\n \n public int check(int[] nums1, int[] nums2){\n int count=0;\n HashMap<Integer,Integer> store = new HashMap<>();\n \n for(int v:nums1){\n store.put((v*v),store.getOrDefault(v*v,0)+1);\n }\n \n for(int j=0; j<nums2.length-1; j++){\n for(int k=j+1; k<nums2.length; k++){\n if(store.get(nums2[j]*nums2[k])!=null){\n count+=store.get(nums2[j]*nums2[k]);\n }\n }\n }\n return count;\n }\n}\n```
0
0
['Java']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
java simple HashMap
java-simple-hashmap-by-trivedi_cs1-pvio
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
trivedi_cs1
NORMAL
2023-12-29T09:35:20.014554+00:00
2023-12-29T09:35:20.014576+00:00
9
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# Code\n```\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n int n1=nums1.length;\n int n2=nums2.length;\n HashMap<Long,Long>map1=new HashMap<>();\n HashMap<Long,Long>map2=new HashMap<>();\n for(int v:nums1)\n {\n long val=(long)((long)v*(long)v);\n map1.put(val,map1.getOrDefault(val,0L)+1L);\n }\n for(int v:nums2)\n {\n long val=(long)((long)v*(long)v);\n map2.put(val,map2.getOrDefault(val,0L)+1L);\n }\n \n HashMap<Long,Long>pmap1=new HashMap<>();\n HashMap<Long,Long>pmap2=new HashMap<>();\n for(int i=0;i<n1;i++)\n {\n for(int j=i+1;j<n1;j++)\n {\n long p=(long)((long)nums1[i]*(long)nums1[j]);\n pmap1.put(p,pmap1.getOrDefault(p,0L)+1L);\n }\n }\n for(int i=0;i<n2;i++)\n {\n for(int j=i+1;j<n2;j++)\n {\n long p=(long)((long)nums2[i]*(long)nums2[j]);\n pmap2.put(p,pmap2.getOrDefault(p,0L)+1L);\n }\n }\n // System.out.println(pmap1);\n // System.out.println(pmap2);\n long ans=0;\n for(long v:map1.keySet())\n {\n if(pmap2.containsKey(v))\n {\n ans+=(long)(pmap2.get(v)*map1.get(v));\n }\n }\n for(long v:map2.keySet())\n {\n if(pmap1.containsKey(v))\n {\n ans+=(long)(pmap1.get(v)*map2.get(v));\n }\n }\n return (int)ans;\n }\n}\n```
0
0
['Java']
0
number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers
Python Simple Approach
python-simple-approach-by-raj_zinzuvadiy-64ax
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
Raj_Zinzuvadiya
NORMAL
2023-12-27T19:23:28.978132+00:00
2023-12-27T19:23:28.978159+00:00
31
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: $$O(n^2)$$ \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:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n\n dic1 = dict()\n dic2 = dict()\n\n\n for i in nums1:\n if dic1.get(i**2) is None:\n dic1[i**2] = 1\n else:\n dic1[i**2] = dic1[i**2] + 1\n\n for i in nums2:\n if dic2.get(i**2) is None:\n dic2[i**2] = 1\n else:\n dic2[i**2] = dic2[i**2] + 1\n\n count = 0\n idx = 0\n len_ = len(nums1)\n \n while idx < len_:\n j = idx + 1\n while j < len_:\n temp = nums1[idx] * nums1[j]\n if dic2.get(temp) is not None:\n count += dic2[temp] \n \n j += 1\n idx +=1\n \n idx = 0\n len_ = len(nums2)\n\n while idx < len_:\n j = idx + 1\n while j < len_:\n temp = nums2[idx] * nums2[j]\n if dic1.get(temp) is not None:\n count += dic1[temp] \n j += 1\n idx +=1\n \n return count\n \n \n```
0
0
['Python3']
0