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
split-array-into-maximum-number-of-subarrays
Swift Solution | Time Complexity: O(N) | Space Complexity: O(1)
swift-solution-time-complexity-on-space-4pgt9
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
amangoel123
NORMAL
2023-10-27T04:54:12.810528+00:00
2023-10-27T04:54:12.810546+00:00
4
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 func maxSubarrays(_ nums: [Int]) -> Int {\n var numsLength = nums.count\n\n var minValue = nums[0]\n var index = 1\n while index < numsLength {\n minValue = (minValue & nums[index])\n index = index + 1\n }\n \n if minValue != 0 {\n return 1\n }\n\n var totalCount = 0\n var value = -1\n index = 0\n\n while index < numsLength {\n if value == -1 {\n value = nums[index]\n if value == minValue {\n totalCount = totalCount + 1\n value = -1\n }\n } else {\n value = (value & nums[index])\n if value == minValue {\n totalCount = totalCount + 1\n value = -1\n }\n }\n index = index + 1\n }\n return totalCount\n }\n}\n```
0
0
['Swift']
0
split-array-into-maximum-number-of-subarrays
Super simple python solution
super-simple-python-solution-by-sekerez-arpb
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
sekerez
NORMAL
2023-10-18T04:17:11.099617+00:00
2023-10-18T04:17:30.622263+00:00
3
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)$$\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```python\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n result, running = 0, 0\n for n in nums:\n running = n & (running or n)\n result += int(running == 0)\n return result or 1\n \n```
0
0
['Python3']
0
split-array-into-maximum-number-of-subarrays
Python | Video Walkthrough
python-video-walkthrough-by-bnchn-2w3u
Click Here For Video Walkthrough\n\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n AND = nums[0]\n ZERO = 0\n curr
bnchn
NORMAL
2023-10-13T22:32:33.511161+00:00
2023-10-13T22:32:33.511179+00:00
2
false
[Click Here For Video Walkthrough](https://youtu.be/lQiAFfyw6wI)\n```\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n AND = nums[0]\n ZERO = 0\n curr = nums[0]\n for i in range(1,len(nums)):\n if curr == 0:\n curr = nums[i]\n ZERO += 1\n curr = curr & nums[i]\n AND = AND & nums[i]\n return 1 if AND > 0 else ZERO + int(curr == 0)\n```
0
0
['Python']
0
split-array-into-maximum-number-of-subarrays
Java Solution for Splitting an Array into Maximum Number of Subarrays
java-solution-for-splitting-an-array-int-llpi
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
mouadabate
NORMAL
2023-10-11T20:52:02.597511+00:00
2023-10-11T20:52:02.597528+00:00
1
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 maxSubarrays(int[] nums) {\n int result =0;\n int temp;\n int min = nums[0];\n int temp2=nums[0];\n int index;\n for(int i: nums){\n temp2 &= i;\n if(temp2 < min){\n min = temp2;\n }\n }\n for(int i=0;i<nums.length;i++){\n index = -1;\n temp = nums[i];\n for(int j=i;j<nums.length;j++){\n temp &= nums[j];\n if(temp == min){\n index = j;\n if(min ==0){\n i=j;\n result++;\n break;\n }\n \n }\n if(j == nums.length -1 && index != -1){\n i=index;\n result ++;\n }\n }\n\n }\n return result;\n\n\n \n }\n}\n```
0
0
['Array', 'Greedy', 'Bit Manipulation', 'Java']
0
split-array-into-maximum-number-of-subarrays
JAVA O(N) SOLUTION
java-on-solution-by-aminultension-ywnp
\n# Code\n\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int prev = nums[0];\n for (int i = 1; i < nums.length; i++) {\n
aminultension
NORMAL
2023-10-10T05:23:47.748988+00:00
2023-10-10T05:23:47.749020+00:00
1
false
\n# Code\n```\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int prev = nums[0];\n for (int i = 1; i < nums.length; i++) {\n prev &= nums[i];\n }\n int min = prev;\n int cnt = 0;\n prev = nums[0];\n for (int i = 1; i < nums.length; i++) {\n if (prev == min) {\n cnt++;\n prev = nums[i];\n } \n prev = (prev & nums[i]);\n }\n if (prev == min) cnt++;\n if (cnt * min > min) return 1;\n return cnt == 0 ? 1 : cnt;\n }\n}\n```
0
0
['Java']
0
split-array-into-maximum-number-of-subarrays
Javascript - Bit Manipulation + Greedy
javascript-bit-manipulation-greedy-by-fa-xihk
Code\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maxSubarrays = function (nums) {\n const AND = nums.reduce((acc, curr) => acc & curr);\n
faustaleonardo
NORMAL
2023-10-09T00:35:50.818607+00:00
2023-10-09T00:35:50.818629+00:00
4
false
# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maxSubarrays = function (nums) {\n const AND = nums.reduce((acc, curr) => acc & curr);\n if (AND > 0) return 1;\n\n let ans = 0;\n let curr = null;\n for (let i = 0; i < nums.length; i++) {\n curr = curr === null ? nums[i] : curr & nums[i];\n\n if (curr === 0) {\n ans++;\n curr = null;\n }\n }\n\n return ans;\n};\n\n```
0
0
['Greedy', 'Bit Manipulation', 'JavaScript']
0
split-array-into-maximum-number-of-subarrays
Simple Python Solution
simple-python-solution-by-walkingmiracle-5z5z
\n\n# Code\n\nclass Solution(object):\n def maxSubarrays(self, nums):\n score, ans = -1, 1\n for i in nums:\n score &= i\n
walkingmiracle
NORMAL
2023-10-08T18:54:41.661314+00:00
2023-10-08T18:54:41.661331+00:00
4
false
\n\n# Code\n```\nclass Solution(object):\n def maxSubarrays(self, nums):\n score, ans = -1, 1\n for i in nums:\n score &= i\n if score == 0:\n score = -1\n ans += 1\n return 1 if ans == 1 else ans - 1\n \n```
0
0
['Python']
0
split-array-into-maximum-number-of-subarrays
Greedy Trick | Count all 0 score to maximize
greedy-trick-count-all-0-score-to-maximi-fxc0
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
0-index
NORMAL
2023-10-08T15:51:10.425394+00:00
2023-10-08T15:51:55.052031+00:00
4
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- o(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- o(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int ans=nums[0]; int n=nums.size();\n for(int i=1;i<n;i++) ans&=nums[i];\n if(ans!=0) return 1;\n int c=0;\n ans=-1;\n for(int i=0;i<n;i++)\n {\n if(ans==-1) ans=nums[i];\n else ans&=nums[i];\n if(ans==0)\n {\n c++; // count whenever we get a min score\n if(i+1<n){ ans=nums[i+1]; } // move to next element\n }\n }\n return c;\n }\n};\n```
0
0
['C++']
0
split-array-into-maximum-number-of-subarrays
beats 100% in Java
beats-100-in-java-by-rajaniket-8t22
Intuition\nSince we have to use and operator so chances of minimising the sum becomes higher as more elements are included because any new element/number may br
rajaniket_
NORMAL
2023-10-08T08:26:10.029523+00:00
2023-10-08T08:26:10.029550+00:00
2
false
# Intuition\nSince we have to use and operator so chances of minimising the sum becomes higher as more elements are included because any new element/number may bring some bit as zero which would eventally makes the bit at that position zero for overall & operator. \n\n# Approach\nWe first try to find the minimum possible value of sum possible and then try to maximise the number of subarrays. To find the minimum value of sum, we would & all the elements of array. If it is greater that 0 then we have no choice but to include all elements so the subarray would be the array itself and the answer would be 1\n\nThe second case arised when the minimum possible value is zero, then it is possible that more that 1 subarray exist with zero value so we would count the number of subarrays where the elements give the value as zero when we and(&) them and that would be answer.\n\n# Complexity\n- Time complexity:\nIterating through the array twice so 2n or o(n).\n\n- Space complexity:\n0(1) as extra space only occupied by variable and independent of number of elements in the array.\n\n# Code\n```\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int min_possible_sum = nums[0];\n for(int i = 1; i<nums.length; i++){\n min_possible_sum = min_possible_sum & nums[i];\n }\n if(min_possible_sum > 0){\n return 1;\n }\n\n // if minimum possible sum is greater than zero then we have only one choice to include all elements so the answer is 1\n\n int t = nums[0];\n int ans = 0;\n for(int i = 1; i<nums.length; i++){\n if(t == 0){\n ans++;\n t = nums[i];\n continue;\n }\n t &= nums[i];\n }\n\n if(t == 0){\n ans++;\n }\n\n return ans;\n \n }\n}\n```
0
0
['Bit Manipulation', 'Java']
0
split-array-into-maximum-number-of-subarrays
Easy Bit Manipulation Solution | C++
easy-bit-manipulation-solution-c-by-arin-q9c0
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
arindam_18
NORMAL
2023-10-07T19:25:36.429337+00:00
2023-10-07T19:25:36.429353+00:00
5
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 maxSubarrays(vector<int>& nums) {\n int a=INT_MAX;\n for(auto i:nums)a&=i;\n if(a!=0)return 1;\n a=INT_MAX;\n int cnt=0;\n for(auto i:nums){\n a&=i;\n if(a==0){\n cnt++;\n a=INT_MAX;\n }\n }\n return cnt;\n }\n};\n```
0
0
['Bit Manipulation', 'Bitmask', 'C++']
0
split-array-into-maximum-number-of-subarrays
Easy C++ solution
easy-c-solution-by-afterfm-vq0m
\n# Code\n\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int res=nums[0];\n for(int i=1;i<nums.size();i++) res=(res&nums
cactuz_blues
NORMAL
2023-10-07T12:58:34.665279+00:00
2023-10-07T12:58:34.665305+00:00
8
false
\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int res=nums[0];\n for(int i=1;i<nums.size();i++) res=(res&nums[i]);\n if(res!=0) return 1;\n int cnt=0;\n int j=0;\n int val=nums[j];\n while(j<nums.size())\n {\n if(val==0)\n {\n if(j+1<nums.size()) val=nums[j+1];\n cnt++;\n }\n j++;\n if(j<nums.size()) val=(val&nums[j]);\n }\n return cnt;\n }\n};\n```
0
0
['C++']
0
split-array-into-maximum-number-of-subarrays
Minimum subarray score
minimum-subarray-score-by-debashishdeka-242a
Intuition\n \n Assume the minimum subarray score is 1\n \n => In this case, if you split more,\n the total score is going
DebashishDeka
NORMAL
2023-10-07T10:38:33.553085+00:00
2023-10-07T10:38:33.553112+00:00
3
false
# Intuition\n \n Assume the minimum subarray score is 1\n \n => In this case, if you split more,\n the total score is going to increase overall\n \n => So dont split at all, and total score will also be 1 (due to AND everything)\n => ans = 1\n\n Assume the minimum subarray score is 2\n => same story\n => ans = 1\n \n Assume the minimum subarray score is 0\n => Having more subarrays with same score (0) does not increase overall score\n => So, we try to split to get all subarrays scores 0.\n => if not, the answer is 1. No split at all => ans = 1\n => If we can, then good \n => try to maximize the 0 score subarrays\n => use greedy to end a subarray as soon as we get 0 score\n => if the last subarray is non zero and we have prev zero subarrays, thats ok\n => we can accommodate last no zero score subarray with the prev zero score subarray\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nNo extra space\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int cur = nums[0];\n int ans = 0;\n int n = nums.size();\n for(int i = 1;i<n;i++) {\n if(cur == 0) {\n ans++;\n cur = nums[i];\n continue;\n }\n cur = cur & nums[i];\n }\n \n if(cur == 0) return ans + 1;\n\n // Adjust last non zero subarray with prev zero score subarray\n if(ans >= 1) return ans;\n\n // No split at all.\n return 1;\n }\n};\n```
0
0
['C++']
0
split-array-into-maximum-number-of-subarrays
Java Simple Solution | Using Bit-manipulation | O(N)
java-simple-solution-using-bit-manipulat-yaza
\n\n# Complexity\n- Time complexity: O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n
Omkar_Alase
NORMAL
2023-10-06T07:59:29.226530+00:00
2023-10-06T07:59:29.226561+00:00
1
false
\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int n = nums.length; \n int cnt = 0;\n for(int i = 0;i < n;){\n int and = nums[i];\n int j;\n for(j = i;j < n;j++){\n and &= nums[j];\n if(and == 0){\n break;\n }\n }\n if(and == 0){\n cnt++;\n }\n i = j + 1;\n\n }\n\n return Math.max(cnt,1);\n }\n}\n```
0
0
['Java']
0
split-array-into-maximum-number-of-subarrays
Rust/Python linear solution with detail explanation why zero
rustpython-linear-solution-with-detail-e-7ius
Intuition\n\nFirst lets answer a simpler qustion. What is the minimum number we can obtain? To answer it you need to understand what the AND operation does to a
salvadordali
NORMAL
2023-10-05T02:17:32.803854+00:00
2023-10-05T02:17:32.803877+00:00
6
false
# Intuition\n\nFirst lets answer a simpler qustion. What is the minimum number we can obtain? To answer it you need to understand what the `AND` operation does to a number: it can only decrease it. \n\nSo the minimum number is `AND` of all the numbers. Now lets assume that this minimum is `v`. If the value is positive then the only possible way to achieve is to take the whole array.\n\nIf the value is zero, it might be possible to divide array into more parts and still get zero (as addition of multiple zeros is zero). So all we need is to greedily take elements until the current_and of them is zero. When you get zero you increase the result and start anew.\n\nAt the end you need to check if it is zero to potentially increment one more time\n\n# Complexity\n\n- Time complexity: $O(n)$\n- Space complexity: $O(1)$\n\n# Code\n```Rust []\nimpl Solution {\n pub fn max_subarrays(nums: Vec<i32>) -> i32 {\n let (mut res, mut curr) = (0, nums[0]);\n for i in 1 .. nums.len() {\n if curr == 0 {\n res += 1;\n curr = nums[i];\n } else {\n curr &= nums[i];\n }\n }\n\n if curr == 0 {\n res += 1;\n }\n return 1.max(res);\n }\n}\n```\n```python []\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n curr, res = nums[0], 0\n for v in nums[1:]:\n if curr == 0:\n res += 1\n curr = v\n else:\n curr &= v\n \n return max(1, res + (1 if curr == 0 else 0))\n```\n
0
0
['Python', 'Rust']
0
split-array-into-maximum-number-of-subarrays
Simple linear time and constant space solution
simple-linear-time-and-constant-space-so-uch2
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
ramanshag001
NORMAL
2023-10-04T17:39:12.894991+00:00
2023-10-04T17:39:12.895010+00:00
4
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 O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int n = nums.size();\n int total= nums[0];\n for(int i=0;i<n;i++){\n total&=nums[i];\n }\n if(total){\n return 1;\n }\n int current = -1;\n int ans = 0;\n for(int i=0;i<n;i++){\n if(current == -1){\n current = nums[i];\n }\n else{\n current = current&nums[i];\n }\n if(current==0){\n current= -1;\n ans++;\n }\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
split-array-into-maximum-number-of-subarrays
C++ Solution
c-solution-by-lotus18-jqxf
Code\n\nclass Solution \n{\npublic:\n int maxSubarrays(vector<int>& nums) \n {\n int andd=1;\n for(auto it: nums) andd&=it;\n if(andd
lotus18
NORMAL
2023-10-04T14:59:17.927388+00:00
2023-10-04T14:59:17.927418+00:00
4
false
# Code\n```\nclass Solution \n{\npublic:\n int maxSubarrays(vector<int>& nums) \n {\n int andd=1;\n for(auto it: nums) andd&=it;\n if(andd!=0) return 1;\n int ans=0, i=0, sum=nums[0];\n while(i<nums.size())\n {\n sum&=nums[i];\n if(sum==0)\n {\n if(i+1<nums.size()) sum=nums[i+1];\n ans++;\n }\n i++;\n }\n return max(1,ans);\n }\n};\n```
0
0
['C++']
0
split-array-into-maximum-number-of-subarrays
Ruby O(n) solution, explained
ruby-on-solution-explained-by-dtkalla-e8lq
Intuition\nThe key to this problem is understanding that expanding the subarray cannot increase its bitwise AND value. (Also, it\'s only possible to have mulip
dtkalla
NORMAL
2023-10-04T12:58:21.419379+00:00
2023-10-04T12:58:21.419407+00:00
8
false
# Intuition\nThe key to this problem is understanding that expanding the subarray cannot increase its bitwise AND value. (Also, it\'s only possible to have muliple subarrays and keep the minimum sum if bitwise AND of the whole array is 0.) So we can just go through and find subarrays with a bitwise AND value of 0.\n\n# Approach\n1. Find the bitwise & of the whole array. Return 1 if this is greater than 0: this means we can\'t have multiple subarrays. (If we split it into multiple subarrays, each will have a value of at least min, and so their sum will be higher.)\n2. Initialize curr, i, and total_subarrs as 0.\n3. Iterate though the array. For each element, find & with that and curr.\n - If curr gets to 0, increment total_subarrs and reset curr.\n4. Return total subarrs\n\n(Note that curr will finish at a value other than 0: either nil, if you used the last element of the array in a subarray, or something else. If it\'s not nil, you can just add the remaining elements from the end of the array to the last subarray that got to 0 -- it will still be 0.)\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\ndef max_subarrays(nums)\n min = nums[0]\n (1...nums.length).each { |i| min &= nums[i] }\n return 1 if min > 0\n \n i = 0\n curr = nums[0]\n total_subarrs = 0\n \n while i < nums.length\n curr &= nums[i]\n i += 1\n if curr == 0\n total_subarrs += 1\n curr = nums[i]\n end\n end\n \n total_subarrs\nend\n```
0
0
['Ruby']
0
split-array-into-maximum-number-of-subarrays
Split Array Into Maximum Number Of Subarrays, C++ Explained Solution
split-array-into-maximum-number-of-subar-7qsz
Upvote If Found Helpful !!!\n\n# Approach\n Describe your approach to solving the problem. \nThe problem here is quite simple and needs some simple observations
ShuklaAmit1311
NORMAL
2023-10-04T08:17:12.165173+00:00
2023-10-04T08:17:12.165192+00:00
7
false
**Upvote If Found Helpful !!!**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe problem here is quite simple and needs some simple observations from Bit Manipulation. First of all, its important to divide problem into two cases : If bitwise **AND** of complete array is **zero** or it is **non-zero**. In case, if bitwise **AND** is non-zero, the only answer possible is the complete array itself or answer is always **1** in such case. But why ? If bitwise AND of complete array is non-zero, then it means that some bits are set in all numbers. Lets say that some bit **k** is set in all **N** numbers. If we divide array into **M** subarrays, then contribution of this bit in sum will occur **M** times while taking whole array, its contribution is limited to only a single time, thus its better to take complete array as we need to minimise sum. \n\nNow for second case when bitwise AND of array is **zero**. In this case we just need to check whenever AND becomes 0, increment count by 1. Implementation goes below : \n\n# Complexity\n- Time complexity: **O(N)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n ios_base::sync_with_stdio(0);\n int n = nums.size(),val = nums[0];\n for(int i = 1; i < n; i++){\n val &= nums[i];\n }\n if(val > 0){\n return 1;\n }\n else{\n int ans = 0;\n for(int i = 0; i < n;){\n int k = nums[i];\n if(k == 0){\n ans++;\n i++;\n continue;\n }\n while(i < n && k > 0){\n k &= nums[i];\n i++;\n }\n if(k == 0){\n ans++;\n }\n }\n return ans;\n }\n }\n};\n```
0
0
['Array', 'Math', 'Bit Manipulation', 'C++']
0
split-array-into-maximum-number-of-subarrays
c++, beats 100%, easy explaination, commmented code
c-beats-100-easy-explaination-commmented-l14v
Intuition\nMin score is the and of all the array elements.\nBecause suppose we have 1 at ith bit even if any one elemnt in the array has 0 at that bit the ith b
professor33
NORMAL
2023-10-04T06:02:05.557238+00:00
2023-10-04T06:02:05.557270+00:00
5
false
# Intuition\nMin score is the and of all the array elements.\nBecause suppose we have 1 at ith bit even if any one elemnt in the array has 0 at that bit the ith bit will now become permanently zero.\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nif min score if non zero return 1 else find sub arrays greedily which have a and value of zero.\n\nBecause we want the sum of scores of subarrays to be minimum. suppose we have a array ans we gotmin score as say 10 and there are max of 3 splits possible but now the sum of score will be 30 and our score of the original array is itself 10.\n\nso if we have min score positive splitting the array will not minimize the sum of scores of subbarrays, it will rather increase it. therefore it is better to return the original array\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n \n int n = nums.size();\n int min_score = INT_MAX;\n\n // finding the smallest and possible which is and of the whole array.\n\n// because suppose we have 1 at ith bit even if any one elemnt in the array has 0 at that bit the ith bit will now become permanently zero.\n\n for(int i = 0; i < n; i++){\n\n min_score &= nums[i];\n }\n\n // why?\n if(min_score != 0){\n return 1;\n }\n\n // because we want the sum of scores of subarrays to be minimum. suppose we have a array ans we gotmin score as say 10 and there are max of 3 splits possible but now the sum of score will be 30 and our score of the original array is itself 10.\n\n // so if we have min score positive splitting the array will not minimize the sum of scores of subbarrays, it will rather increase it. therefore it is better to return the original array\n\n int temp = INT_MAX;\n int ans = 0;\n\n for(int i = 0; i < n; i++){\n\n temp &= nums[i];\n\n if(temp == 0){\n ans++;\n temp = INT_MAX;\n }\n }\n\n return ans;\n }\n};\n```
0
0
['Bit Manipulation', 'C++']
0
split-array-into-maximum-number-of-subarrays
A Pointless and Terrible One-Liner
a-pointless-and-terrible-one-liner-by-tr-c88y
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co
trentono
NORMAL
2023-10-03T20:53:29.249648+00:00
2023-10-03T20:53:29.249678+00:00
10
false
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n return sum((x := locals().get(\'x\', -1) & n or -1) == -1 for n in nums) or 1\n\n```
0
0
['Python3']
0
split-array-into-maximum-number-of-subarrays
The World Needs Another Python Solution
the-world-needs-another-python-solution-6dv7z
Approach\n Describe your approach to solving the problem. \nReturns the maximum partition into subarrays with and sum equal to zero, or returns 1 if the and sum
trentono
NORMAL
2023-10-03T20:09:13.337545+00:00
2023-10-03T20:28:36.879497+00:00
8
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nReturns the maximum partition into subarrays with and sum equal to zero, or returns 1 if the and sum of the array is greater than zero.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n x = -1\n subs = 0\n for n in nums:\n x &= n\n if x == 0:\n subs += 1\n x = -1\n \n return subs or 1\n\n```
0
0
['Python3']
0
split-array-into-maximum-number-of-subarrays
minimum score = bitwise AND of all elements | C++
minimum-score-bitwise-and-of-all-element-hbfi
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
_shant_11
NORMAL
2023-10-03T19:27:32.383957+00:00
2023-10-03T19:27:32.383975+00:00
4
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 maxSubarrays(vector<int>& nums) {\n int minScore = INT_MAX;\n int n = nums.size();\n for(int i=0; i<n; i++){\n minScore &= nums[i];\n }\n int res = 0;\n if(minScore != 0) return 1;\n int curr = INT_MAX;\n for(int i=0; i<n; i++){\n curr &= nums[i];\n if(curr == minScore){\n res++;\n curr = INT_MAX;\n }\n }\n return res;\n }\n};\n```
0
0
['C++']
0
split-array-into-maximum-number-of-subarrays
prefix , and of subarray>= and of array
prefix-and-of-subarray-and-of-array-by-y-088y
Intuition\n Describe your first thoughts on how to solve this problem. \n\nprefix and \n\n# Code\n\nclass Solution {\npublic:\n int maxSubarrays(vector<int>&
yaswanth58
NORMAL
2023-10-03T18:14:47.437028+00:00
2023-10-03T18:14:47.437050+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nprefix and \n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int ans=0,ad=nums[0];\n for(auto el:nums)\n {\n ad=ad&el; \n }\n if(ad) return 1;\n int prefix=INT_MAX;\n for(int i=0;i<nums.size();i++)\n {\n prefix=prefix&nums[i];\n cout<<prefix<<" ";\n if(prefix==0) {\n ans++;\n prefix=INT_MAX; \n } \n }\n return ans;\n }\n};\n```
0
0
['C++']
0
split-array-into-maximum-number-of-subarrays
My Solution
my-solution-by-hope_ma-pf2i
\n/**\n * Time Complexity: O(n)\n * Space Complexity: O(1)\n * where `n` is the length of the vector `nums`\n */\nclass Solution {\n public:\n int maxSubarrays
hope_ma
NORMAL
2023-10-03T11:49:43.098886+00:00
2023-10-05T07:57:38.704209+00:00
1
false
```\n/**\n * Time Complexity: O(n)\n * Space Complexity: O(1)\n * where `n` is the length of the vector `nums`\n */\nclass Solution {\n public:\n int maxSubarrays(const vector<int> &nums) {\n constexpr uint32_t multi_split_target = 0U;\n int ret = 0;\n uint32_t score = -1U;\n for (const int num : nums) {\n score &= num;\n if (score == multi_split_target) {\n ++ret;\n score = -1U;\n }\n }\n return ret == 0 ? 1 : ret;\n }\n};\n```
0
0
[]
0
split-array-into-maximum-number-of-subarrays
[C++] Time Complexity - O(N) and constant space complexity
c-time-complexity-on-and-constant-space-6tqpr
We want the maximum subarray, so the input array given to us, can also be considered as a subarray, so if the bitwise and of all the elements is not zero then t
shresthchomal
NORMAL
2023-10-03T08:07:02.743167+00:00
2023-10-03T08:07:02.743190+00:00
2
false
We want the maximum subarray, so the input array given to us, can also be considered as a subarray, so if the bitwise and of all the elements is not zero then the sum of the scores of subarray cannot be minimized if we divide it in multiple subarrays, but if the value is 0 then we can say that the scores of minimum 2 subarrays can be 0.\n\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int n=nums.size();\n if(n == 1)\n return 1;\n int x=nums[0];\n for(int i=1;i<n;i++){\n x=x&nums[i];\n }\n if(x)\n return 1;\n int cnt=0,val=0;\n for(int i=0;i<n;i++){\n int j=i;\n int num=nums[i];\n if(num == 0){\n cnt++;\n continue;\n }\n while(j<n){\n num=num&nums[j];\n if(num == x){\n break;\n }\n j++;\n }\n if(j!=n){\n cnt++;\n }\n val+=num;\n i=j;\n }\n \n return cnt;\n }\n};\n\nTC - O(n) WHERE n is the size of array\nSC - O(n) WHERE n is the size of the array
0
0
['C++']
0
split-array-into-maximum-number-of-subarrays
[C++|Java|Python3] Greedy
cjavapython3-greedy-by-ye15-vzur
C++\n\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int ans = 0, prefix = -1; \n for (auto& x : nums) {\n pre
ye15
NORMAL
2023-10-03T00:58:46.517921+00:00
2023-10-03T00:58:46.517942+00:00
11
false
C++\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int ans = 0, prefix = -1; \n for (auto& x : nums) {\n prefix &= x; \n if (prefix == 0) {\n ++ans; \n prefix = -1; \n }\n }\n return max(1, ans); \n }\n};\n```\nJava\n```\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int ans = 0, prefix = -1; \n for (var x : nums) {\n prefix &= x; \n if (prefix == 0) {\n ++ans; \n prefix = -1; \n }\n }\n return Math.max(1, ans); \n }\n}\n```\nPython3\n```\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n ans = 0\n prefix = -1\n for x in nums: \n prefix &= x \n if prefix == 0: \n ans += 1\n prefix = -1\n return max(1, ans)\n```
0
0
['C', 'Java', 'Python3']
0
split-array-into-maximum-number-of-subarrays
100%beats
100beats-by-vishal1431-2bd3
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
Vishal1431
NORMAL
2023-10-02T11:42:50.461844+00:00
2023-10-02T11:42:50.461864+00:00
3
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 maxSubarrays(vector<int>&a) {\n int k=a[0];\n int ans=0;\n for(int i=1;i<a.size();i++){\n k&=a[i];\n }\n\n if(k!=0)return 1;\n int q=INT_MAX;\n\n for(int i=0;i<a.size();i++){\n q&=a[i];\n if(q==0){ ans++;q=INT_MAX; }\n }\n \n return ans;\n }\n};\n```
0
0
['Greedy', 'Bit Manipulation', 'C++']
0
split-array-into-maximum-number-of-subarrays
Java | JavaScript | C++ | C# Solution.
java-javascript-c-c-solution-by-lachezar-7p4a
Java []\npublic class Solution {\n\n private static final int NO_POSSIBLE_DIVISIONS_OF_THE_ARRAY = 1;\n\n public int maxSubarrays(int[] inputValues) {\n\n
LachezarTsK
NORMAL
2023-10-02T07:52:44.982149+00:00
2023-10-02T07:52:44.982176+00:00
12
false
```Java []\npublic class Solution {\n\n private static final int NO_POSSIBLE_DIVISIONS_OF_THE_ARRAY = 1;\n\n public int maxSubarrays(int[] inputValues) {\n\n int minScore = Integer.MAX_VALUE;\n for (int currentValue : inputValues) {\n minScore &= currentValue;\n }\n\n if (minScore != 0) {\n return NO_POSSIBLE_DIVISIONS_OF_THE_ARRAY;\n }\n\n int currentScore = Integer.MAX_VALUE;\n int maxNumberOfSubarraysWithMinScore = 0;\n\n for (int currentValue : inputValues) {\n currentScore &= currentValue;\n if (currentScore == 0) {\n ++maxNumberOfSubarraysWithMinScore;\n currentScore = Integer.MAX_VALUE;\n }\n }\n\n return maxNumberOfSubarraysWithMinScore;\n }\n}\n```\n```JavaScript []\n/**\n * @param {number[]} inputValues\n * @return {number}\n */\nvar maxSubarrays = function (inputValues) {\n\n const NO_POSSIBLE_DIVISIONS_OF_THE_ARRAY = 1;\n \n let minScore = Number.MAX_SAFE_INTEGER;\n for (let currentValue of inputValues) {\n minScore &= currentValue;\n }\n\n if (minScore !== 0) {\n return NO_POSSIBLE_DIVISIONS_OF_THE_ARRAY;\n }\n\n let currentScore = Number.MAX_SAFE_INTEGER;\n let maxNumberOfSubarraysWithMinScore = 0;\n\n for (let currentValue of inputValues) {\n currentScore &= currentValue;\n if (currentScore === 0) {\n ++maxNumberOfSubarraysWithMinScore;\n currentScore = Number.MAX_SAFE_INTEGER;\n }\n }\n\n return maxNumberOfSubarraysWithMinScore;\n};\n```\n```C++ []\n#include <vector>\nusing namespace std;\n\nclass Solution {\n \n static const int NO_POSSIBLE_DIVISIONS_OF_THE_ARRAY = 1;\n\npublic:\n int maxSubarrays(const vector<int>& inputValues) const {\n\n int minScore = INT_MAX;\n for (const auto& currentValue : inputValues) {\n minScore &= currentValue;\n }\n\n if (minScore != 0) {\n return NO_POSSIBLE_DIVISIONS_OF_THE_ARRAY;\n }\n\n int currentScore = INT_MAX;\n int maxNumberOfSubarraysWithMinScore = 0;\n\n for (const auto& currentValue : inputValues) {\n currentScore &= currentValue;\n if (currentScore == 0) {\n ++maxNumberOfSubarraysWithMinScore;\n currentScore = INT_MAX;\n }\n }\n\n return maxNumberOfSubarraysWithMinScore;\n }\n};\n```\n```C# []\nusing System;\n\npublic class Solution\n{\n private static readonly int NO_POSSIBLE_DIVISIONS_OF_THE_ARRAY = 1;\n\n public int MaxSubarrays(int[] inputValues)\n {\n int minScore = int.MaxValue;\n foreach (int currentValue in inputValues)\n {\n minScore &= currentValue;\n }\n\n if (minScore != 0)\n {\n return NO_POSSIBLE_DIVISIONS_OF_THE_ARRAY;\n }\n\n int currentScore = int.MaxValue;\n int maxNumberOfSubarraysWithMinScore = 0;\n\n foreach (int currentValue in inputValues)\n {\n currentScore &= currentValue;\n if (currentScore == 0)\n {\n ++maxNumberOfSubarraysWithMinScore;\n currentScore = int.MaxValue;\n }\n }\n\n return maxNumberOfSubarraysWithMinScore;\n }\n}\n```
0
0
['C++', 'Java', 'JavaScript', 'C#']
0
split-array-into-maximum-number-of-subarrays
Python bit manipulation
python-bit-manipulation-by-nanzhuangdala-guoi
Intuition\n Describe your first thoughts on how to solve this problem. \nAll the credit in this post goes to lee215. I simply write down my notes.\n1. x & y <=
nanzhuangdalao
NORMAL
2023-10-02T07:34:19.821914+00:00
2023-10-02T07:34:19.821932+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAll the credit in this post goes to lee215. I simply write down my notes.\n1. **x & y <= x** and **x && y <= y**;\n2. nums[0] AND nums[1] AND ... AND nums[-1] < = nums[l] AND nums[l + 1] AND ... AND nums[r].\nEquivalent to **score(array) <= score(subarray)**;\n3. If score(array) >= 1, then there\'s no need to split it because the sum of the scores of subarrays must be larger than score(array);\n4. If score(array) == 0, then we may try spliting it.\n5. When we can split the array into subarrays? \nWe can calculate the prefix score, setting the initial prefix score as 2^31 -1 (all the bits are 1 in binary format). Then we start traversing the array, when the prefix score becomes zero, then we can split it, and then we shall reset the prefix to 2^31 - 1.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n prefix = 2 ** 31 - 1\n res = 0\n for num in nums:\n prefix &= num\n if prefix == 0:\n res += 1\n prefix = 2 ** 31 - 1\n \n return max(1, res)\n```
0
0
['Python3']
0
split-array-into-maximum-number-of-subarrays
C++ solution bitwise AND
c-solution-bitwise-and-by-sting285-zcpx
Complexity\n- Time complexity:\nO(n)\n\n# Code\n\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int val = nums[0];\n for(
Sting285
NORMAL
2023-10-02T05:18:01.297061+00:00
2023-10-02T05:18:01.297089+00:00
6
false
# Complexity\n- Time complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int val = nums[0];\n for(int i=1;i<nums.size();i++){\n val = val & nums[i];\n }\n\n if(val!=0)\n return 1;\n \n int res = 0, ptr=0;\n while(ptr < nums.size()){\n int val = nums[ptr];\n ++ptr;\n while(val != 0 && ptr < nums.size()){\n val&=nums[ptr];\n ++ptr;\n }\n if(val == 0)\n ++res;\n }\n\n return res;\n }\n};\n```
0
0
['C++']
0
customers-who-bought-all-products
Simple Solution with two line query
simple-solution-with-two-line-query-by-d-b1cj
Please Upvote my solution, if you find it helpful ;)\n\n# Intuition\nTo find the customers who have bought all the products, we need to compare the distinct pro
deepankyadav
NORMAL
2023-06-07T08:15:20.954145+00:00
2023-06-07T08:17:18.447944+00:00
54,624
false
## ***Please Upvote my solution, if you find it helpful ;)***\n\n# Intuition\nTo find the customers who have bought all the products, we need to compare the distinct products bought by each customer with the total number of products available. If the counts match, it means the customer has bought all the products.\n\n# Approach\n1. Select the customer_id from the Customer table.\n1. Group the results by customer_id.\n1. Apply a HAVING clause to filter out customers who have not bought all the products.\n1. In the HAVING clause, use ***COUNT(DISTINCT product_key)*** to count the number of distinct product keys for each customer.\n1. Compare this count with the total count of product keys in the Product table obtained through a subquery.\n1. If the counts match, it means the customer has bought all the products.\n# Complexity\n- Time complexity:\nThe time complexity of this solution depends on the size of the Customer and Product tables. Let\'s assume there are n customers and m products. The counting of distinct product keys for each customer takes $$O(n)$$ time, and the subquery to count the total number of products takes $$O(m)$$ time. Therefore, the overall time complexity can be approximated as $$O(n + m)$$.\n\n- Space complexity:\nThe space complexity of this solution is considered $$O(1)$$ or constant. It only requires a constant amount of additional space for storing intermediate results and the subquery. The space usage does not depend on the size of the input tables.\n\n# Code\n```\n# Write your MySQL query statement below\n\n\'SELECT customer_id FROM Customer GROUP BY customer_id\nHAVING COUNT(distinct product_key) = (SELECT COUNT(product_key) FROM Product)\'\n```\n***Please Upvote my solution, if you find it helpful ;)***\n![6a87bc25-d70b-424f-9e60-7da6f345b82a_1673875931.8933976.jpeg](https://assets.leetcode.com/users/images/9b775724-1c6b-46bb-8e7b-5f6f8be29f1c_1686125409.4786477.jpeg)\n
481
5
['Database', 'MySQL']
36
customers-who-bought-all-products
MySQL subquery
mysql-subquery-by-ms25-7ia9
\nselect customer_id\nfrom customer c\ngroup by customer_id\nhaving count(distinct product_key)=(select count(distinct product_key) from product)\n\n\n
ms25
NORMAL
2019-05-18T22:14:13.626664+00:00
2019-05-18T22:14:13.626739+00:00
21,553
false
```\nselect customer_id\nfrom customer c\ngroup by customer_id\nhaving count(distinct product_key)=(select count(distinct product_key) from product)\n\n\n```
104
3
[]
19
customers-who-bought-all-products
Most posted solutions are wrong!!!
most-posted-solutions-are-wrong-by-sophi-myj7
Ignore my post if you only interested in getting your code pass the leetcode test, but not interested in how to do things right!!!\n\n\nMost solutions posted he
sophiesu0827
NORMAL
2019-12-17T20:10:49.681155+00:00
2019-12-17T21:06:18.687813+00:00
6,339
false
**Ignore my post if you only interested in getting your code pass the leetcode test, but not interested in how to do things right!!!**\n\n\nMost solutions posted here have used \'count distinct product_key\'. However, this method **should NOT be considered as the correct answer**. For example, if the **Product** table contains **5 & 7** instead of **5 & 6**, using \'count distinct product_key\', you will still get results of customer_id **1 & 3**, which is definitely **WRONG!!!**\n\n![image](https://assets.leetcode.com/users/sophiesu0827/image_1576613740.png)\n\n**The correct procedures should be:**\n1. do a **cartesian product** (**cross join** in MySQL) on all customer_id eg.1,2,3 from table Customer and all product_key from table "Product ". \n![image](https://assets.leetcode.com/users/sophiesu0827/image_1576613877.png)\n\n\n2. find difference between table **Customer** and the **cartesian product**\n![image](https://assets.leetcode.com/users/sophiesu0827/image_1576613041.png)\n\n3. list all customer_id not in the difference set (red row in the above table)\n![image](https://assets.leetcode.com/users/sophiesu0827/image_1576614001.png)\n\n\n\n**MySQL code:**\n\n```\nSELECT DISTINCT customer_id FROM Customer WHERE customer_id NOT IN (\nSELECT customer_id FROM (\nSELECT DISTINCT * FROM \n(SELECT DISTINCT customer_id FROM Customer) C\nCROSS JOIN Product P) C2\nWHERE (customer_id,product_key) NOT IN (SELECT customer_id,product_key FROM Customer));\n```
59
28
[]
24
customers-who-bought-all-products
✅ 100% EASY || FAST 🔥|| CLEAN SOLUTION 🌟
100-easy-fast-clean-solution-by-kartik_k-mk92
IF THIS WILL BE HELPFUL TO YOU, PLEASE UPVOTE !\n# Code\n\n/* Write your PL/SQL query statement below */\nSELECT customer_id FROM Customer GROUP BY customer_id
kartik_ksk7
NORMAL
2023-08-05T05:20:41.541944+00:00
2023-08-05T05:46:52.889785+00:00
8,992
false
IF THIS WILL BE HELPFUL TO YOU, PLEASE UPVOTE !\n# Code\n```\n/* Write your PL/SQL query statement below */\nSELECT customer_id FROM Customer GROUP BY customer_id HAVING \n\nCOUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)\n```\n![5kej8w.jpg](https://assets.leetcode.com/users/images/8277a962-a3d0-44d3-b441-e4bbae047a8b_1691212838.5783477.jpeg)\n
57
0
['Database', 'Oracle']
3
customers-who-bought-all-products
SQL ✅ || Easy to Understand ✅ || GROUP BY, SUM, DISTINCT, SUBQUERY
sql-easy-to-understand-group-by-sum-dist-3cm5
Intuition\r\nWe can first group by customer_ids and then check them with having.\r\n\r\nThe pass shows 2 different ways to achieve the two solutions.\r\n\r\n\r\
jasurbekaktamov081
NORMAL
2023-05-31T12:40:28.357990+00:00
2023-05-31T12:40:28.358029+00:00
5,210
false
# Intuition\r\nWe can first group by customer_ids and then check them with having.\r\n\r\nThe pass shows 2 different ways to achieve the two solutions.\r\n\r\n![image.png](https://assets.leetcode.com/users/images/8ebca5a0-4abf-40f7-b5e2-ea062298ee6a_1685536566.1817262.png)\r\n\r\n\r\n# First Solution\r\n```\r\nSELECT \r\n customer_id\r\nFROM Customer\r\nGROUP BY customer_id\r\nHAVING SUM(DISTINCT product_key) = (\r\n SELECT\r\n SUM(product_key)\r\n FROM Product\r\n); \r\n```\r\n# Second Solution\r\n```\r\nselect \r\ncustomer_id\r\n#SubQuery Begin -->\r\nfrom (select \r\ncase \r\n when count(distinct product_key) = (select count(product_key) from Product)\r\n then customer_id end as customer_id\r\nfrom Customer c\r\ngroup by customer_id) as subquery\r\n# SubQuery --> End\r\nwhere customer_id is not null\r\n\r\n); \r\n```\r\n
28
0
['Database', 'MySQL']
5
customers-who-bought-all-products
Easy and Simple Solution | Beginner-friendly🚀
easy-and-simple-solution-beginner-friend-1pn9
CodeIf you found this solution helpful, please give it an upvote! 🌟✨ It really motivates me to share more solutions like this. 😊👍 Happy coding! 💻🐱‍🏍 IntuitionWe
Yadav_Akash_
NORMAL
2025-02-10T18:16:35.216514+00:00
2025-02-10T18:16:35.216514+00:00
3,303
false
# Code ```mysql [] # Write your MySQL query statement below select customer_id from Customer group by customer_id having count(distinct product_key) = (select count(product_key) from Product); ``` **If you found this solution helpful, please give it an upvote! 🌟✨ It really motivates me to share more solutions like this. 😊👍 Happy coding! 💻🐱‍🏍** <img src="https://assets.leetcode.com/users/images/6e8c623a-1111-4d21-9a5b-54e00e7feabb_1738093236.165277.jpeg" width=250px> # Intuition We need to find customers who have purchased **all available products** listed in the `Product` table. This means: 1. Counting the number of **distinct products** each customer has purchased. 2. Comparing it with the **total number of products** in the `Product` table. 3. Returning only those `customer_id`s who have bought every product at least once. # Approach 1. **Count the total number of products** - Use `SELECT COUNT(product_key) FROM Product` to get the total product count. 2. **Count distinct products purchased by each customer** - Use `GROUP BY customer_id` to process each customer separately. - Use `HAVING COUNT(DISTINCT product_key) = (total products)` to filter customers who bought every product. 3. **Return only the qualifying `customer_id`s** - The `HAVING` clause ensures we include only customers who have purchased all products. # Complexity Analysis - **Counting total products (`SELECT COUNT(product_key) FROM Product`)** - Runs in **O(P)**, where `P` is the number of products. - **Grouping and counting distinct purchases (`GROUP BY customer_id HAVING COUNT(DISTINCT product_key)`)** - Sorting and grouping operations run in **O(N log C)**, where `C` is the number of unique customers. - Counting distinct products per customer runs in **O(N log K)**, where `K` is the number of unique products per customer. ### **Overall Complexity:** - The dominant factor is **grouping and distinct counting**, leading to an approximate **O(N log C + P) ≈ O(N log N)** complexity in the worst case.
15
0
['MySQL']
3
customers-who-bought-all-products
Medium🔥||🔝TOP 2023🤝|| Explained 📝|| SQL50/29✅
mediumtop-2023-explained-sql5029-by-komr-becv
Hello LeetCode fans,\nBelow I presented a solution to the problem (1045. Customers Who Bought All Products).\nIf you found it useful or informative,\nClick the
komronabdulloev
NORMAL
2023-10-26T21:50:18.485278+00:00
2023-10-26T21:50:18.485298+00:00
2,697
false
# Hello LeetCode fans,\nBelow I presented a solution to the problem (1045. Customers Who Bought All Products).\nIf you found it `useful` or `informative`,\nClick the "`UPVOTE`" button below and it means I was able to `help someone`.\nYour UPVOTES encourage me and others who are `working hard` to improve their problem solving skills.\n# Code\n```\nSELECT customer_id\n FROM customer c\n GROUP BY customer_id\n HAVING count(distinct product_key)=(SELECT count(distinct product_key) \n FROM product)\n\n```
15
0
['MySQL']
2
customers-who-bought-all-products
pandas || groupby || T/S: 96% / 85%
pandas-groupby-ts-96-85-by-spaulding-vedl
Here\'s the plan:\n1. We filter for redundant rows.\n\n2. For each customer count the number of distinct products purchased by each customer. \n2. We compare t
Spaulding_
NORMAL
2024-02-13T17:48:25.393081+00:00
2024-05-31T21:56:06.689726+00:00
2,643
false
Here\'s the plan:\n1. We filter for redundant rows.\n\n2. For each customer count the number of distinct products purchased by each customer. \n2. We compare these counts with `len(product),` the count of the set of distinct products that can be purchased;\n```\nimport pandas as pd\n\ndef find_customers(customer: pd.DataFrame, \n product: pd.DataFrame) -> pd.DataFrame:\n \n df = customer.drop_duplicates(keep = \'first\'\n ).groupby(\'customer_id\').count().reset_index()\n\n return df[df.product_key == len(product)][[\'customer_id\']]\n```\n[https://leetcode.com/problems/customers-who-bought-all-products/submissions/1085527726/?lang=pythondata\n](https://leetcode.com/problems/customers-who-bought-all-products/submissions/1085527726/?lang=pythondata\n)\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*U*), in which *N* ~ `len(customer)` and *U* ~ the number of unique customer ids.
14
0
['Pandas']
1
customers-who-bought-all-products
Natural Language Solution
natural-language-solution-by-lazy_bad_b0-2fa5
Approach\nwe have to chose those customer_id which have same number of product key as total number of product(using sub_query from Product table)\n\n\n# Code\n\
lazy_bad_b0y
NORMAL
2024-01-11T23:27:33.251505+00:00
2024-01-11T23:27:33.251537+00:00
1,443
false
# Approach\nwe have to chose those customer_id which have same number of product key as total number of product(using sub_query from Product table)\n\n\n# Code\n```\n# Write your MySQL query statement below\n\nselect customer_id \nfrom Customer \ngroup by customer_id\nhaving count(distinct (product_key))=(select count(product_key) from Product )\n\n```\n![Screenshot 2023-12-03 042253.png](https://assets.leetcode.com/users/images/c2ee8042-2ef2-46ee-a7c7-8276bd8ab190_1705015649.8040946.png)\n
14
1
['MySQL']
0
customers-who-bought-all-products
Simple MySQL Solution
simple-mysql-solution-by-kothavade-hnqb
Simple join and group by, followed by selecting customers whose unique(distinct) product bought count is equal to total number of products in product table.\n\n
kothavade
NORMAL
2019-05-18T18:35:44.364789+00:00
2019-06-06T22:18:52.484363+00:00
4,308
false
Simple join and group by, followed by selecting customers whose unique(distinct) product bought count is equal to total number of products in product table.\n\n```\nselect customer_id\nfrom Customer \ngroup by customer_id\nhaving count(distinct(product_key)) = (select count(product_key) from Product)\n```
12
0
[]
5
customers-who-bought-all-products
Super Easy approach.
super-easy-approach-by-lovepreet12a-02u9
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
Lovepreet12a
NORMAL
2023-06-05T16:19:31.878394+00:00
2023-06-05T16:19:31.878451+00:00
3,518
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```\n/* Write your T-SQL query statement below */\n\nSELECT customer_id \nFROM Customer C\nGROUP BY customer_id\nHAVING COUNT(DISTINCT(product_key)) = (SELECT COUNT(DISTINCT(product_key)) FROM Product)\n\n```
10
0
['MS SQL Server']
1
customers-who-bought-all-products
✅EASY AND SIMPLE SOLUTION✅
easy-and-simple-solution-by-deleted_user-0ogc
\n# Code\n\n# Write your MySQL query statement below\nselect \n customer_id \nfrom \n Customer \ngroup by \n customer_id\nhaving \n count(distinct
deleted_user
NORMAL
2024-05-26T15:29:03.621366+00:00
2024-05-26T15:29:03.621384+00:00
2,409
false
\n# Code\n```\n# Write your MySQL query statement below\nselect \n customer_id \nfrom \n Customer \ngroup by \n customer_id\nhaving \n count(distinct product_key) = (select count(product_key) from product)\n```
9
0
['MySQL']
0
customers-who-bought-all-products
SQL: Identifying Customers Purchasing All Products
sql-identifying-customers-purchasing-all-kke9
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
aleos-dev
NORMAL
2023-12-18T16:07:50.442589+00:00
2023-12-18T16:07:50.442615+00:00
1,049
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(C * logC)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSubquery: This part calculates the total number of unique products. The time complexity is O(1).\n\nMain Query: The GROUP BY operation groups customer records, which typically takes O(Clog\u2061C) time, where C is the number of rows in the Customer table.\n\n\n- Space complexity: $$O(C)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Write your MySQL query statement below\nSELECT\n customer_id\nFROM\n Customer\nGROUP BY\n customer_id\nHAVING\n COUNT(DISTINCT product_key) = (\n SELECT\n COUNT(product_key)\n FROM\n Product\n );\n```\n![upvote_leetcode.png](https://assets.leetcode.com/users/images/9769bcc5-dd45-4794-9291-b8d0bcd32d66_1702915660.8288038.png)\n
9
0
['MySQL']
0
customers-who-bought-all-products
Simple Solution using ARRAY_AGG()
simple-solution-using-array_agg-by-danie-2n98
\n# Approach\nNot used count of the products, Instead Ensured exact items are present or not. Using ARRAY_AGG() function aggreagted all the product_id then comp
Daniel_Charles_J
NORMAL
2024-09-07T05:23:14.331190+00:00
2024-09-07T05:23:14.331214+00:00
1,258
false
\n# Approach\nNot used count of the products, Instead Ensured exact items are present or not. Using ARRAY_AGG() function aggreagted all the product_id then compared with the Product table.\n\nIf we tried to match with Counts, may be fail in some other test cases, here this won\'t fail at any cost\n\n\n# Code\n```postgresql []\n-- Write your PostgreSQL query statement below\nSELECT c.customer_id FROM Customer c LEFT JOIN Product p ON c.product_key = p.product_key \nGROUP BY c.customer_id \nHAVING ARRAY(SELECT product_key FROM Product ORDER BY product_key) <@ ARRAY_AGG(c.product_key)ORDER BY 1\n```
8
0
['PostgreSQL']
3
customers-who-bought-all-products
✅✅✅EASY MYSQL SOLUTION
easy-mysql-solution-by-swayam28-1o18
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
swayam28
NORMAL
2024-08-16T12:15:02.960576+00:00
2024-08-16T12:15:02.960606+00:00
2,604
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![upv.png](https://assets.leetcode.com/users/images/8d92dfce-67bb-40a5-85e2-34b97efe29d0_1723810500.556567.png)\n\n```\n# Write your MySQL query statement below\nSELECT c.customer_id FROM Customer c GROUP BY c.customer_id HAVING COUNT(DISTINCT c.product_key) = (SELECT COUNT(DISTINCT product_key) FROM Product);\n```
8
0
['MySQL']
0
customers-who-bought-all-products
Complete breakdown | Beats 91% ✅ | Easy to understand
complete-breakdown-beats-91-easy-to-unde-3p14
Steps: \n\n1. Number of Products in the Product Table\n2. Group Customers and Count the Number of Distinct Products\n3. Customer IDs That Bought All Products sq
Pacman45
NORMAL
2023-12-28T15:54:55.044031+00:00
2023-12-28T19:27:55.318506+00:00
1,261
false
# Steps: \n\n1. Number of Products in the Product Table\n2. Group Customers and Count the Number of Distinct Products\n3. Customer IDs That Bought All Products sql\n\n# Complexity: \n\n- Time complexity: $$O(N+M)$$\n- Space complexity: $$O(N)$$\n\n_Try coming up with a justification for these complexities on your own. Explanation in detail after code._ \n\n# Code\n```\n# Write your MySQL query statement below\nSELECT customer_id FROM Customer \nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(product_key) FROM Product)\n```\n\n## Step 1: Count the Number of Products in the Product Table\n\n```\nSELECT \n COUNT(product_key) AS total_products\nFROM \n Product;\n```\n\n## Result:\n\n```\n+---------------+\n| total_products|\n+---------------+\n| 2 |\n+---------------+\n```\n\n## Step 2: Group Customers and Count the Number of Distinct Products They Bought\n\n```\nSELECT \n customer_id,\n COUNT(DISTINCT product_key) AS distinct_products_bought\nFROM \n Customer\nGROUP BY \n customer_id;\n```\n\n## Result:\n\n```\n+-------------+------------------------+\n| customer_id | distinct_products_bought|\n+-------------+------------------------+\n| 1 | 2 |\n| 2 | 1 |\n| 3 | 2 |\n+-------------+------------------------+\n```\n\n## Step 3: Select Customer IDs That Bought All Products\n```\nSELECT \n customer_id\nFROM \n Customer\nGROUP BY \n customer_id\nHAVING \n COUNT(DISTINCT product_key) = (SELECT COUNT(product_key) FROM Product);\n```\n\n## Result:\n\n```\n+-------------+\n| customer_id |\n+-------------+\n| 1 |\n| 3 |\n+-------------+\n```\n\n\n---\n\n\n# Complexity breakdown: \n\n1. Time complexity: \n\n- Let, \n**N**: Number of rows in the Customer table, \n**M**: Number of rows in the Product table.\n\n- `Grouping by Customer ID`: $$O(N)$$ - Scans through all rows in the Customer table, grouping by customer_id.\n\n- `Counting Distinct Product Keys`: $$O(N)$$ - Performs COUNT(DISTINCT product_key) for each grouped customer.\n\n- `Subquery for Total Product Keys`: $$O(M)$$ - Subquery (SELECT COUNT(product_key) FROM Product) counts the **Total number of product keys in the Product table.**\n\n- `HAVING Clause`: $$O(N)$$ - Number of customers containing all distinct product keys.\n\n- Overall Time Complexity: $$O(N + M)$$ \n\n2. Space complexity:\n\n- The query most likely uses a hash map or similar data structure to group rows by customer_id and store distinct product keys for each customer. \n\nLet, **N: Number of rows in the Customer table**\n\nSpace Complexity: $$O(N)$$\n\n\n
8
0
['MySQL']
1
customers-who-bought-all-products
Pandas one-liner, f-string inside query
pandas-one-liner-f-string-inside-query-b-739n
Intuition\nWe just want to count how many unique products customer bought and check if this is the number of all products (in this question we dont have to worr
piocarz
NORMAL
2023-08-18T10:21:22.029792+00:00
2023-10-31T19:13:14.384621+00:00
594
false
# Intuition\nWe just want to count how many unique products customer bought and check if this is the number of all products (in this question we dont have to worry for products that were bought but are not included in product list, and dont have to worry about duplicates in product list)\n\n# Approach\nGroup by customer and count number of unique products. Then compare it with length of product list and if they are the same, we got customer who bought all products.\n\nwhat is worth noticing - we can use f-string as our query. Then inside such query, we can directly specify expression calculating length of product list.\n# Code\n```\nimport pandas as pd\n\ndef find_customers(customer: pd.DataFrame, product: pd.DataFrame) -> pd.DataFrame:\n return customer.groupby("customer_id",as_index = False).product_key.nunique().query(f"product_key == {len(product)}")[["customer_id"]]\n```
8
0
['Pandas']
1
customers-who-bought-all-products
Robust + simple answer
robust-simple-answer-by-yechenh-stqz
sql\nselect customer_id\nfrom Customer \nwhere product_key in (select distinct product_key from Product)\ngroup by customer_id\nhaving count(distinct product_ke
yechenh
NORMAL
2019-08-02T04:10:37.438273+00:00
2019-08-02T04:10:37.438303+00:00
1,656
false
```sql\nselect customer_id\nfrom Customer \nwhere product_key in (select distinct product_key from Product)\ngroup by customer_id\nhaving count(distinct product_key) = (select count(distinct product_key) from product);\n```
7
0
[]
1
customers-who-bought-all-products
MySQL simple Solution
mysql-simple-solution-by-chaitanya_91-dci3
Intuition\n Describe your first thoughts on how to solve this problem. \nIdentify all distinct products in the product catalog.\nDetermine which customers have
Chaitanya_91
NORMAL
2024-07-30T11:03:07.410699+00:00
2024-07-30T11:03:07.410733+00:00
2,351
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIdentify all distinct products in the product catalog.\nDetermine which customers have purchased each of these distinct products.\nFilter out customers who have bought all the products.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCount Total Distinct Products: First, we count the number of distinct products in the product catalog.\nGroup By Customer and Count Purchased Products: Then, for each customer, we count the number of distinct products they have purchased.\nFilter Customers: Finally, we filter out those customers whose count of distinct purchased products equals the total number of distinct products in the catalog.\n\n# Complexity\n- Time complexity: O(n + m)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n + m)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Write your MySQL query statement below\nSELECT c.customer_id\nFROM Customer c\nGROUP BY c.customer_id\nHAVING COUNT(DISTINCT c.product_key) = (SELECT COUNT(DISTINCT product_key) FROM Product);\n\n```
6
0
['MySQL']
0
customers-who-bought-all-products
SQL SERVER - easiest solution
sql-server-easiest-solution-by-lshigami-jsw8
\n\n# Code\n\n/* Write your T-SQL query statement below */\nDECLARE @counter INT;\nSELECT @counter = COUNT(* ) FROM product;\n\nselect customer_id \nfrom custom
lshigami
NORMAL
2024-04-03T15:25:37.985713+00:00
2024-04-03T15:25:37.985750+00:00
1,939
false
\n\n# Code\n```\n/* Write your T-SQL query statement below */\nDECLARE @counter INT;\nSELECT @counter = COUNT(* ) FROM product;\n\nselect customer_id \nfrom customer\ngroup by customer_id\nhaving count(distinct product_key) = @counter\n```
6
0
['MS SQL Server']
2
customers-who-bought-all-products
A Simple and Easy Solution using GROUP BY, DISTINCT and COUNT() | BEGINNER LEVEL 👍
a-simple-and-easy-solution-using-group-b-aa39
Explanation\n\nWe use group by customer_id to disinguish each customer_id and check the number of distinct products they have bought.\n\nSELECT customer_id FROM
jasubrinner
NORMAL
2023-05-28T14:11:10.089868+00:00
2023-05-28T14:11:10.089908+00:00
2,664
false
# Explanation\n\nWe use group by customer_id to disinguish each customer_id and check the number of distinct products they have bought.\n\nSELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key)\n\nAnd then we check if this count matches with the count of available products in the product table.\n\nSELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)\n\nIF the count matches, then it is believed that customer has in fact purchased all the available products \uD83D\uDC4D.\n\n\n# Code\n```\n# Write your MySQL query statement below\n\nSELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)\n```
6
0
['MySQL']
1
customers-who-bought-all-products
I don't like joins, so here you go: 4-liner HAVING() solution
i-dont-like-joins-so-here-you-go-4-liner-2xly
select customer_id\nfrom Customer\ngroup by 1\nhaving count(distinct product_key) = (select count(distinct product_key) from Product)
fy09
NORMAL
2022-04-12T19:00:37.134420+00:00
2022-04-12T19:00:47.393666+00:00
1,312
false
select customer_id\nfrom Customer\ngroup by 1\nhaving count(distinct product_key) = (select count(distinct product_key) from Product)
6
0
[]
1
customers-who-bought-all-products
Using GROUP_CONCAT() from accurate results
using-group_concat-from-accurate-results-oj4i
\nWITH c as (SELECT customer_id, \nGROUP_CONCAT(DISTINCT product_key \n order by product_key\n separator \',\') as produ
taylor168
NORMAL
2021-03-07T05:11:21.170054+00:00
2021-03-07T05:11:21.170089+00:00
475
false
```\nWITH c as (SELECT customer_id, \nGROUP_CONCAT(DISTINCT product_key \n order by product_key\n separator \',\') as products\nFROM Customer\nGROUP BY customer_id),\np as (\nSELECT \nGROUP_CONCAT(DISTINCT product_key \n\t\t\t\torder by product_key\n separator \',\') as uni_product\nFROM Product)\n\nSELECT customer_id \nFROM c, p\nWHERE c.products = p.uni_product\n```
6
0
[]
0
customers-who-bought-all-products
👉🏻FAST AND EASY TO UNDERSTAND SOLUTION || NO JOIN || GROUP BY || HAVING || MySQL
fast-and-easy-to-understand-solution-no-oyflo
IntuitionApproachComplexity Time complexity: Space complexity: Code
Siddarth9911
NORMAL
2024-12-27T17:54:59.976861+00:00
2024-12-27T17:54:59.976861+00:00
1,645
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 ```mysql [] SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT( DISTINCT product_key) = ( SELECT COUNT(product_key) FROM Product ) ```
5
0
['MySQL']
0
customers-who-bought-all-products
easy to understandable solution please visit once
easy-to-understandable-solution-please-v-dpv6
\n\n# Code\nmysql []\n# Write your MySQL query statement below\nselect customer_id from Customer\ngroup by customer_id having count(distinct product_key)=(selec
mantosh_kumar04
NORMAL
2024-08-26T16:08:47.067499+00:00
2024-08-26T16:08:47.067525+00:00
951
false
\n\n# Code\n```mysql []\n# Write your MySQL query statement below\nselect customer_id from Customer\ngroup by customer_id having count(distinct product_key)=(select count(product_key) from product);\n```\n![001a585f-aef3-47c5-980d-77cfdbbe28fe_1702552970.456921.jpeg](https://assets.leetcode.com/users/images/927cff4d-78e4-4257-ab00-c20273b224a1_1724688518.66271.jpeg)\n
5
0
['MySQL']
0
customers-who-bought-all-products
🐘PostgreSQL ❗ Beats 97.20% ❗ Simple solution with GROUP BY and HAVING filtering by COUNT
postgresql-beats-9720-simple-solution-wi-1s4v
Approach\nThis SQL query you\'re writing aims to find customers who have purchased every product in the product table. To achieve this, you need to count the di
IliaAvdeev
NORMAL
2024-05-27T11:42:51.914630+00:00
2024-05-27T11:42:51.914654+00:00
628
false
# Approach\nThis SQL query you\'re writing aims to find customers who have purchased every product in the product table. To achieve this, you need to count the distinct `product_key` each customer has purchased and compare it to the total number of products.\n\n1. **Main Query**:\n - `SELECT customer_id`: Selects the customer IDs.\n - `GROUP BY customer_id`: Groups the results by `customer_id` to aggregate their purchases.\n\n2. **HAVING Clause**:\n - `HAVING COUNT(DISTINCT product_key)`: Counts the distinct `product_key` values each customer has.\n - `= (SELECT COUNT(*) FROM product)`: Compares this count to the total number of products in the `product` table. This subquery returns the total number of products available.\n\nThis query ensures that only those customers who have purchased every single product are selected.\n\n\n# Code\n```\nSELECT customer_id FROM customer\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM product)\n```
5
0
['PostgreSQL']
0
customers-who-bought-all-products
Simple & Easy - MySQL Solution
simple-easy-mysql-solution-by-kg-profile-qsx0
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
KG-Profile
NORMAL
2024-04-19T11:34:50.406185+00:00
2024-04-19T11:34:50.406211+00:00
949
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```\n# Write your MySQL query statement below\nselect customer_id from customer\ngroup by 1\nhaving count(distinct product_key) = (select count(product_key) from product)\n```
5
0
['MySQL']
0
customers-who-bought-all-products
💻Think like SQL Engine🔥Learn Writing Dynamic queries(INNER JOIN✅)
think-like-sql-enginelearn-writing-dynam-zs22
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
k_a_m_o_l
NORMAL
2023-11-24T17:31:24.425371+00:00
2023-11-24T17:31:24.425395+00:00
997
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```\n# Write your MySQL query statement below\n\nselect customer_id\nfrom customer c\ninner join product p on c.product_key = p.product_key\nwhere c.product_key is not null\ngroup by customer_id\nhaving count(distinct c.product_key) = (select count(product_key) from Product)\norder by customer_id asc\n\n\n```
5
1
['MySQL']
1
customers-who-bought-all-products
Pandas | SQL | Explained Step By Step | Customers Who Bought All Products
pandas-sql-explained-step-by-step-custom-8fez
\nsee the Successfully Accepted Submission\nPython\nimport pandas as pd\n\ndef find_customers(customer: pd.DataFrame, product: pd.DataFrame) -> pd.DataFrame:\n
Khosiyat
NORMAL
2023-10-01T19:48:12.436739+00:00
2023-10-01T19:48:12.436762+00:00
780
false
\n[see the Successfully Accepted Submission](https://leetcode.com/submissions/detail/1056960636/)\n```Python\nimport pandas as pd\n\ndef find_customers(customer: pd.DataFrame, product: pd.DataFrame) -> pd.DataFrame:\n \n grouped_customers = customer.groupby(\'customer_id\')\n \n unique_customer_id = grouped_customers.nunique()\n \n size_product = len(product)\n \n bought_all_products = (unique_customer_id == size_product)\n \n wanted_cusotomer_df = bought_all_products.reset_index()\n \n wanted_cusotomer_id = wanted_cusotomer_df[wanted_cusotomer_df[\'product_key\']][[\'customer_id\']]\n \n return wanted_cusotomer_id\n```\n\n**Intuituin**\n \n Group the \'customer\' DataFrame by \'customer_id\'.\n```\n grouped_customers = customer.groupby(\'customer_id\')\n```\n Count the number of unique products purchased by each customer.\n```\n unique_customer_id = grouped_customers.nunique()\n``` \nCalculate the total number of products in the \'product\' DataFrame.\n```\n size_product = len(product)\n```\nCheck if each customer has bought all the unique products.\n```\n bought_all_products = (unique_customer_id == size_product)\n```\nReset the index of the \'bought_all_products\' DataFrame.\n```\n wanted_cusotomer_df = bought_all_products.reset_index()\n```\nSelect the \'customer_id\' column from the \'wanted_cusotomer_df\' DataFrame for customers who bought all products.\n```\n wanted_cusotomer_id = wanted_cusotomer_df[wanted_cusotomer_df[\'product_key\']][[\'customer_id\']]\n```\n\n**SQL**\n\n[see the Successfully Accepted Submission](https://leetcode.com/submissions/detail/1062906245/)\n\n```SQL\nSELECT customer_id\nFROM Customer\nGROUP BY customer_id\nHAVING COUNT(\n DISTINCT product_key) = (SELECT COUNT(product_key) \n FROM Product)\n```\n\n![image](https://assets.leetcode.com/users/images/b1e4af48-4da1-486c-bc97-b11ae02febd0_1696186577.992237.jpeg)\n\n\n# Pandas & SQL | SOLVED & EXPLAINED LIST\n\n**EASY**\n\n- [Combine Two Tables](https://leetcode.com/problems/combine-two-tables/solutions/4051076/pandas-sql-easy-combine-two-tables/)\n\n- [Employees Earning More Than Their Managers](https://leetcode.com/problems/employees-earning-more-than-their-managers/solutions/4051991/pandas-sql-easy-employees-earning-more-than-their-managers/)\n\n- [Duplicate Emails](https://leetcode.com/problems/duplicate-emails/solutions/4055225/pandas-easy-duplicate-emails/)\n\n- [Customers Who Never Order](https://leetcode.com/problems/customers-who-never-order/solutions/4055429/pandas-sql-easy-customers-who-never-order-easy-explained/)\n\n- [Delete Duplicate Emails](https://leetcode.com/problems/delete-duplicate-emails/solutions/4055572/pandas-sql-easy-delete-duplicate-emails-easy/)\n- [Rising Temperature](https://leetcode.com/problems/rising-temperature/solutions/4056328/pandas-sql-easy-rising-temperature-easy/)\n\n- [ Game Play Analysis I](https://leetcode.com/problems/game-play-analysis-i/solutions/4056422/pandas-sql-easy-game-play-analysis-i-easy/)\n\n- [Find Customer Referee](https://leetcode.com/problems/find-customer-referee/solutions/4056516/pandas-sql-easy-find-customer-referee-easy/)\n\n- [Classes More Than 5 Students](https://leetcode.com/problems/classes-more-than-5-students/solutions/4058381/pandas-sql-easy-classes-more-than-5-students-easy/)\n- [Employee Bonus](https://leetcode.com/problems/employee-bonus/solutions/4058430/pandas-sql-easy-employee-bonus/)\n\n- [Sales Person](https://leetcode.com/problems/sales-person/solutions/4058824/pandas-sql-easy-sales-person/)\n\n- [Biggest Single Number](https://leetcode.com/problems/biggest-single-number/solutions/4063950/pandas-sql-easy-biggest-single-number/)\n\n- [Not Boring Movies](https://leetcode.com/problems/not-boring-movies/solutions/4065350/pandas-sql-easy-not-boring-movies/)\n- [Swap Salary](https://leetcode.com/problems/swap-salary/solutions/4065423/pandas-sql-easy-swap-salary/)\n\n- [Actors & Directors Cooperated min Three Times](https://leetcode.com/problems/actors-and-directors-who-cooperated-at-least-three-times/solutions/4065511/pandas-sql-easy-explained-step-by-step-actors-directors-cooperated-min-three-times/)\n\n- [Product Sales Analysis I](https://leetcode.com/problems/product-sales-analysis-i/solutions/4065545/pandas-sql-easy-product-sales-analysis-i/)\n\n- [Project Employees I](https://leetcode.com/problems/project-employees-i/solutions/4065635/pandas-sql-easy-project-employees-i/)\n- [Sales Analysis III](https://leetcode.com/problems/sales-analysis-iii/solutions/4065755/sales-analysis-iii-pandas-easy/)\n\n- [Reformat Department Table](https://leetcode.com/problems/reformat-department-table/solutions/4066153/pandas-sql-easy-explained-step-by-step-reformat-department-table/)\n\n- [Top Travellers](https://leetcode.com/problems/top-travellers/solutions/4066252/top-travellers-pandas-easy-eaxplained-step-by-step/)\n\n- [Replace Employee ID With The Unique Identifier](https://leetcode.com/problems/replace-employee-id-with-the-unique-identifier/solutions/4066321/pandas-sql-easy-replace-employee-id-with-the-unique-identifier/)\n- [Group Sold Products By The Date](https://leetcode.com/problems/group-sold-products-by-the-date/solutions/4066344/pandas-sql-easy-explained-step-by-step-group-sold-products-by-the-date/)\n\n- [Customer Placing the Largest Number of Orders](https://leetcode.com/problems/customer-placing-the-largest-number-of-orders/solutions/4068822/pandas-sql-easy-explained-step-by-step-customer-placing-the-largest-number-of-orders/)\n\n- [Article Views I](https://leetcode.com/problems/article-views-i/solutions/4069777/pandas-sql-easy-article-views-i/)\n\n- [User Activity for the Past 30 Days I](https://leetcode.com/problems/user-activity-for-the-past-30-days-i/solutions/4069797/pandas-sql-easy-user-activity-for-the-past-30-days-i/)\n\n- [Find Users With Valid E-Mails](https://leetcode.com/problems/find-users-with-valid-e-mails/solutions/4069810/pandas-sql-easy-find-users-with-valid-e-mails/)\n\n- [Patients With a Condition](https://leetcode.com/problems/patients-with-a-condition/solutions/4069817/pandas-sql-easy-patients-with-a-condition/)\n\n- [Customer Who Visited but Did Not Make Any Transactions](https://leetcode.com/problems/customer-who-visited-but-did-not-make-any-transactions/solutions/4072542/pandas-sql-easy-customer-who-visited-but-did-not-make-any-transactions/)\n\n\n- [Bank Account Summary II](https://leetcode.com/problems/bank-account-summary-ii/solutions/4072569/pandas-sql-easy-bank-account-summary-ii/)\n\n- [Invalid Tweets](https://leetcode.com/problems/invalid-tweets/solutions/4072599/pandas-sql-easy-invalid-tweets/)\n\n- [Daily Leads and Partners](https://leetcode.com/problems/daily-leads-and-partners/solutions/4072981/pandas-sql-easy-daily-leads-and-partners/)\n\n- [Recyclable and Low Fat Products](https://leetcode.com/problems/recyclable-and-low-fat-products/solutions/4073003/pandas-sql-easy-recyclable-and-low-fat-products/)\n\n- [Rearrange Products Table](https://leetcode.com/problems/rearrange-products-table/solutions/4073028/pandas-sql-easy-rearrange-products-table/)\n- [Calculate Special Bonus](https://leetcode.com/problems/calculate-special-bonus/solutions/4073595/pandas-sql-easy-calculate-special-bonus/)\n\n- [Count Unique Subjects](https://leetcode.com/problems/number-of-unique-subjects-taught-by-each-teacher/solutions/4073666/pandas-sql-easy-count-unique-subjects/)\n\n- [Count Unique Subjects](https://leetcode.com/problems/number-of-unique-subjects-taught-by-each-teacher/solutions/4073666/pandas-sql-easy-count-unique-subjects/)\n\n- [Fix Names in a Table](https://leetcode.com/problems/fix-names-in-a-table/solutions/4073695/pandas-sql-easy-fix-names-in-a-table/)\n- [Primary Department for Each Employee](https://leetcode.com/problems/primary-department-for-each-employee/solutions/4076183/pandas-sql-easy-primary-department-for-each-employee/)\n\n- [The Latest Login in 2020](https://leetcode.com/problems/the-latest-login-in-2020/solutions/4076240/pandas-sql-easy-the-latest-login-in-2020/)\n\n- [Find Total Time Spent by Each Employee](https://leetcode.com/problems/find-total-time-spent-by-each-employee/solutions/4076313/pandas-sql-easy-find-total-time-spent-by-each-employee/)\n\n- [Find Followers Count](https://leetcode.com/problems/find-followers-count/solutions/4076342/pandas-sql-easy-find-followers-count/)\n- [Percentage of Users Attended a Contest](https://leetcode.com/problems/percentage-of-users-attended-a-contest/solutions/4077301/pandas-sql-easy-percentage-of-users-attended-a-contest/)\n\n- [Employees With Missing Information](https://leetcode.com/problems/employees-with-missing-information/solutions/4077308/pandas-sql-easy-employees-with-missing-information/)\n\n- [Average Time of Process per Machine](https://leetcode.com/problems/average-time-of-process-per-machine/solutions/4077402/pandas-sql-easy-average-time-of-process-per-machine/)\n
5
0
['MySQL']
0
customers-who-bought-all-products
Easy Solution🔥|| MySQL || Having Clause || 100% Fast✅
easy-solution-mysql-having-clause-100-fa-85tn
Intuition \uD83E\uDDE0\n Describe your first thoughts on how to solve this problem. \nWe have to count the distinct product keys for each customers and then che
utkarsh911
NORMAL
2023-08-07T14:45:42.158953+00:00
2023-08-07T14:45:42.158980+00:00
793
false
# Intuition \uD83E\uDDE0\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe have to count the distinct product keys for each customers and then check if it matches with all the types of products in the product table.\n# Approach \uD83D\uDEE4\uFE0F\n<!-- Describe your approach to solving the problem. -->\nTo check that the count of distinct product keys of a customer is equal to the total types of products in Products table. We will just check if the count distinct of product key in Customer table is equal to count of Product Key in Products Table. So for that we have to add the condition in having clause.\n\n# Code \uD83E\uDDD1\u200D\uD83D\uDCBB\n```\nselect customer_id\nfrom Customer\ngroup by customer_id\nhaving count(distinct product_key) = (select count(product_key) from Product)\n```\n\n![image.png](https://assets.leetcode.com/users/images/d72c738f-2795-4c86-9fad-3e746bf42661_1691419489.5374012.png)\n
5
0
['Database', 'MySQL']
0
customers-who-bought-all-products
EASY MYSQL
easy-mysql-by-yf9-zriz
\tSELECT customer_id\n\tFROM Customer\n\tGROUP BY customer_id\n\tHAVING count(DISTINCT product_key) = (SELECT count(*) FROM Product)
yf9
NORMAL
2022-07-24T20:47:26.098576+00:00
2022-07-24T20:47:26.098603+00:00
812
false
\tSELECT customer_id\n\tFROM Customer\n\tGROUP BY customer_id\n\tHAVING count(DISTINCT product_key) = (SELECT count(*) FROM Product)
5
0
[]
0
customers-who-bought-all-products
Easy to understand solution- No cartesian join needed
easy-to-understand-solution-no-cartesian-f6n4
Select customer_id from (select distinct \n customer_id,product_key from customer) g group by customer_id\nhaving count(*) = (select cou
varunjoshi12
NORMAL
2020-06-10T06:32:57.108518+00:00
2020-06-10T06:32:57.108569+00:00
654
false
Select customer_id from (select distinct \n customer_id,product_key from customer) g group by customer_id\nhaving count(*) = (select count( product_key) from product)\n\n1- Use the inner query to get rid of dups ( one customer purchasing same product more than once)\n2- Then get the number of times each customerid appears in the customer table.\n3- The records with the count equal to number of products should be in our answer.
5
1
[]
0
customers-who-bought-all-products
SQL query to find the customer_ids that bought all the products
sql-query-to-find-the-customer_ids-that-rkaau
IntuitionApproachCOUNT(DISTINCT product_key) counts the number of unique products each customer has purchased. The subquery (SELECT COUNT(*) FROM Product) retri
avinash516
NORMAL
2025-03-18T09:47:49.605873+00:00
2025-03-18T09:47:49.605873+00:00
767
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach COUNT(DISTINCT product_key) counts the number of unique products each customer has purchased. The subquery (SELECT COUNT(*) FROM Product) retrieves the total number of unique products available in the Product table. The HAVING clause ensures that only those customer_ids who have purchased all products are included in the result. <!-- 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 ```mysql [] # Write your MySQL query statement below SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product); ```
4
0
['MySQL']
0
customers-who-bought-all-products
Simple | Intuitive
simple-intuitive-by-pkannuri-389t
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
pkannuri
NORMAL
2024-05-19T14:36:23.080417+00:00
2024-05-19T14:36:23.080437+00:00
1,290
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```\n# Write your MySQL query statement below\nselect customer_id\nfrom customer\ngroup by customer_id\nhaving count(distinct(product_key)) = (select count(*) from product);\n```
4
0
['MySQL']
0
customers-who-bought-all-products
Beginner friendly solution with deep explaination :
beginner-friendly-solution-with-deep-exp-7fg3
To solve the problem of identifying customers who have bought all the products listed in the Product table, we can break down the problem into several steps and
deleted_user
NORMAL
2024-04-21T16:29:25.735236+00:00
2024-06-16T08:43:50.346223+00:00
963
false
To solve the problem of identifying customers who have bought all the products listed in the `Product` table, we can break down the problem into several steps and then write an SQL query that accomplishes this task. Here\u2019s a detailed explanation:\n\n## Intuition\nThe key idea is to compare the number of distinct products each customer has bought to the total number of products available. If a customer has bought every product at least once, the count of distinct products they have purchased will match the total count of products.\n\n## Approach\n1. **Count Total Products**: First, we need to determine how many distinct products exist in the `Product` table.\n2. **Count Distinct Products per Customer**: For each customer, we need to count the number of distinct products they have purchased.\n3. **Compare Counts**: Identify customers whose count of distinct purchased products matches the total count of products.\n\n## Complexity\n- **Time Complexity**: \n - Counting total products requires a full scan of the `Product` table: \\(O(m)\\), where \\(m\\) is the number of products.\n - Counting distinct products per customer requires scanning the `Customer` table and grouping by `customer_id`: \\(O(n)\\), where \\(n\\) is the number of purchases.\n - Combining these results involves filtering the grouped results: \\(O(n)\\).\n Overall, the time complexity is \\(O(n + m)\\).\n\n- **Space Complexity**:\n - The space required to store intermediate counts and results is \\(O(k)\\), where \\(k\\) is the number of customers.\n - Additionally, any sorting or grouping operations might require temporary space proportional to the input size.\n\n## Code\nHere\u2019s the SQL query that implements the approach:\n\n```sql\n-- Write your MySQL query statement below\n\n-- Step 1: Get the total number of distinct products\nWITH TotalProducts AS (\n SELECT COUNT(*) AS product_count\n FROM Product\n),\n\n-- Step 2: Count the distinct products purchased by each customer\nCustomerProductCounts AS (\n SELECT customer_id, COUNT(DISTINCT product_key) AS distinct_product_count\n FROM Customer\n GROUP BY customer_id\n)\n\n-- Step 3: Select customers whose count of distinct purchased products matches the total number of products\nSELECT customer_id\nFROM CustomerProductCounts, TotalProducts\nWHERE distinct_product_count = product_count;\n```\n\n### Explanation\n1. **TotalProducts CTE**:\n - This common table expression (CTE) calculates the total number of distinct products by counting rows in the `Product` table.\n \n2. **CustomerProductCounts CTE**:\n - This CTE groups purchases by `customer_id` and counts the number of distinct `product_key` values for each customer.\n\n3. **Final Selection**:\n - The main query joins the two CTEs and selects customers where the count of distinct products they have purchased matches the total product count.\n\nThis approach ensures that we accurately identify customers who have purchased all available products.\n\n\nCODE : \n\n```.sql\n\n# Write your MySQL query statement below\nSELECT customer_id FROM Customer GROUP BY customer_id\nHAVING COUNT(distinct product_key) = (SELECT COUNT(product_key) FROM Product)\n\n\n```
4
0
['MySQL']
1
customers-who-bought-all-products
MySQL Clean Solution | Detail Explanation
mysql-clean-solution-detail-explanation-21lfc
Intuition\n Describe your first thoughts on how to solve this problem. \nWe\'re tasked with finding the customer IDs from the Customer table who have bought all
Shree_Govind_Jee
NORMAL
2024-04-16T16:22:45.366805+00:00
2024-04-16T16:22:45.366835+00:00
1,325
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe\'re tasked with finding the **`customer IDs`** from the **`Customer table`** who have bought all the products listed in the **`Product table`**. To achieve this, we need to identify customers who have purchased all the **`products`** in the **`product list`**.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Use a **`GROUP BY`** clause to group the records in the **`Customer table`** by **`customer_id`**.\n- Use the **`HAVING`** clause to filter out **`customers`** who have purchased *`all products`*.\n- This is done by **`counting`** the **`distinct product_key`** values for each **`customer`** and comparing it with the total **`count`** of **`products`** in the **`Product table`**.\n\n# Code\n```\n# Write your MySQL query statement below\nSELECT customer_id\nFROM Customer\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (\n SELECT COUNT(product_key)\n FROM Product\n);\n```
4
0
['Database', 'MySQL']
0
customers-who-bought-all-products
💯AMAZING SOLUTION💯 || 😨SQL😨 || 💥BEATS 1000.0%💥|| 🫵GROUP BY, HAVING🫵
amazing-solution-sql-beats-10000-group-b-uq9r
\n\n# Code\n\n# Write your MySQL query statement below\nselect customer_id \nfrom Customer\ngroup by customer_id \nhaving count(distinct product_key) in (\n se
IvanYY
NORMAL
2023-10-19T11:49:03.816056+00:00
2023-10-19T11:49:03.816077+00:00
657
false
\n\n# Code\n```\n# Write your MySQL query statement below\nselect customer_id \nfrom Customer\ngroup by customer_id \nhaving count(distinct product_key) in (\n select count(distinct product_key)\n from Product \n)\n```\n![st,small,845x845-pad,1000x1000,f8f8f8.jpg](https://assets.leetcode.com/users/images/ec255417-b7c2-4e1d-a87b-c86d86625cac_1697716140.3746212.jpeg)\n
4
0
['MySQL']
2
customers-who-bought-all-products
SOLUTION WITH SIMPLE JOIN ( SQL SERVER )
solution-with-simple-join-sql-server-by-s1kaf
Intuition\r\n Describe your first thoughts on how to solve this problem. \r\n\r\n# Approach\r\n Describe your approach to solving the problem. \r\n\r\n# Complex
cooking_Guy_9ice
NORMAL
2023-04-20T15:52:48.481582+00:00
2023-04-20T15:52:48.481633+00:00
1,608
false
# Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\n\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\n\r\n# Complexity\r\n- Time complexity:\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\n\r\n- Space complexity:\r\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\r\n\r\n# Code\r\n```\r\n/* Write your T-SQL query statement below */\r\n\r\n\r\n\r\n SELECT \r\n T2.customer_id\r\n FROM\r\n product T1 \r\n INNER JOIN\r\n (\r\n SELECT\r\n DISTINCT *\r\n FROM\r\n Customer\r\n ) T2 ON T2.product_key = T1.product_key\r\n GROUP BY\r\n T2.customer_id\r\n HAVING COUNT(T1.product_key) = (SELECT COUNT(product_key) FROM Product)\r\n\r\n```
4
0
['MS SQL Server']
1
customers-who-bought-all-products
simple 4 line solution
simple-4-line-solution-by-evelyncxy1028-6zbe
select customer_id\nfrom customer \ngroup by customer_id\nhaving count(distinct product_key) = (select count(distinct product_key) from product)
evelyncxy1028
NORMAL
2021-11-10T07:53:59.868769+00:00
2021-11-10T07:53:59.868812+00:00
840
false
select customer_id\nfrom customer \ngroup by customer_id\nhaving count(distinct product_key) = (select count(distinct product_key) from product)
4
0
[]
0
customers-who-bought-all-products
MSSQL answer
mssql-answer-by-user4273yk-iv2w
\nSELECT customer_id\nFROM Customer\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(DISTINCT product_key)FROM Product)\n\n
user4273yk
NORMAL
2019-12-19T04:47:29.726138+00:00
2019-12-19T04:47:55.016464+00:00
471
false
```\nSELECT customer_id\nFROM Customer\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(DISTINCT product_key)FROM Product)\n```\n
4
0
['MS SQL Server']
0
customers-who-bought-all-products
super easy solution
super-easy-solution-by-python_data_engin-cnni
\nselect \ncustomer_id\nfrom customer \ngroup by customer_id\nhaving count(distinct product_key) = (select count(*) from product)\n;\n
python_data_engineer
NORMAL
2019-11-24T23:25:31.017691+00:00
2019-11-24T23:25:31.017724+00:00
863
false
```\nselect \ncustomer_id\nfrom customer \ngroup by customer_id\nhaving count(distinct product_key) = (select count(*) from product)\n;\n```
4
0
[]
0
customers-who-bought-all-products
Easy and Simple Solution
easy-and-simple-solution-by-mayankluthya-ooin
Please Like ❤️IntuitionWe need to find customers who have purchased all available products.Approach Group by customer_id to aggregate purchases per customer. Co
mayankluthyagi
NORMAL
2025-02-10T15:17:38.876272+00:00
2025-02-10T15:17:38.876272+00:00
472
false
```mysql # Write your MySQL query statement below SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(product_key) FROM Product); ``` # Please Like ❤️ ![Please Like](https://media.tenor.com/heEyHbV8iaUAAAAM/puss-in-boots-shrek.gif) # Intuition We need to find customers who have purchased **all** available products. # Approach 1. **Group by `customer_id`** to aggregate purchases per customer. 2. **Count distinct `product_key`** for each customer. 3. **Compare this count** with the total number of products in the `Product` table using a subquery. 4. **Return customers** where the counts match. # Complexity - **Time Complexity:** $$O(n)$$ – We scan `Customer` and `Product` tables once. - **Space Complexity:** $$O(1)$$ – No extra storage used.
3
0
['MySQL']
0
customers-who-bought-all-products
Pandas, Polars, PostgreSQL
pandas-polars-postgresql-by-speedyy-k2vv
RememberThis table may contain duplicates rows.\n# Pandas\npy []\nimport pandas as pd\n\ndef find_customers(customer: pd.DataFrame, product: pd.DataFrame) -> pd
speedyy
NORMAL
2024-11-06T09:39:16.358047+00:00
2024-11-06T11:00:41.207389+00:00
595
false
- Remember`This table may contain duplicates rows.`\n# Pandas\n```py []\nimport pandas as pd\n\ndef find_customers(customer: pd.DataFrame, product: pd.DataFrame) -> pd.DataFrame:\n return ( customer.groupby(by=\'customer_id\', as_index=False, sort=False)\n .agg(product_numbers = (\'product_key\', \'nunique\'))\n .query("product_numbers == @product.size")\n .filter(items=[\'customer_id\'], axis=1) # returns dataframe even with one column.\n )\n```\n- SEEEEE? WE CAN USE FUNCTIONS INSIDE `query()` using `@`. I did it accidentally! You can even write `df[\'a\'].min()` something like this too!\n```py []\nimport pandas as pd\n\ndef find_customers(customer: pd.DataFrame, product: pd.DataFrame) -> pd.DataFrame:\n return ( customer.drop_duplicates()\n .groupby(by=\'customer_id\', as_index=False, sort=False)\n .agg(product_numbers = (\'product_key\', \'size\'))\n .query("product_numbers == @product.size")\n .filter(items=[\'customer_id\'], axis=1)\n )\n```\n\n# Polars\n```js\nimport polars as pl\nfrom polars import col\n\ndef find_customers(customer: pl.LazyFrame, product: pl.LazyFrame) -> pl.LazyFrame:\n product_size = product.select(col(\'product_key\').len()) .collect()\n\n return ( customer.group_by(\'customer_id\')\n .agg( product_numbers = col(\'product_key\').n_unique() )\n .filter( col(\'product_numbers\') == product_size ) // product_size is a subquery, so need to write .collect() UP there\n .select( col(\'customer_id\') )\n )\n\nfind_customers(pl.LazyFrame(customer), pl.LazyFrame(product)) .collect()\n```\n\n# PostgreSQL (Execution Order : FROM -> GROUP BY -> HAVING -> SELECT)\n- In Pandas and Polars we `filtered again on the GROUP BY(and agg()) result`. In PostgreSQL we filter on the `GROUP BY result` through `HAVING` clause.\n```postgresql\n-- Write your PostgreSQL query statement below\nSELECT customer_id\nFROM customer\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(product_key) FROM product);\n```\n\n```js\n You cant REFERENCE an ALIAS from CTE in HAVING clause :\n```\n![image.png](https://assets.leetcode.com/users/images/60901a20-8c6a-4a05-bc22-cf55baf03594_1730885931.3530004.png)\n\n
3
0
['PostgreSQL', 'Pandas']
0
customers-who-bought-all-products
EASY SQL Solution
easy-sql-solution-by-hiya99-6i4y
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
Hiya99
NORMAL
2024-09-05T09:38:25.946539+00:00
2024-09-05T09:38:25.946563+00:00
2,325
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```mysql []\n# Write your MySQL query statement below\nSELECT customer_id\nFROM Customer\nGROUP BY customer_id \nHAVING COUNT(DISTINCT product_key)= (SELECT COUNT(*) FROM Product) \n\n```
3
0
['MySQL']
1
customers-who-bought-all-products
Ultimate Simple Solution || Beats 95% || GROUP BY HAVING
ultimate-simple-solution-beats-95-group-sfp08
Code\n\n# Write your MySQL query statement below\nSELECT \ncustomer_id\nFROM Customer\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(
wan01786
NORMAL
2024-07-15T19:14:26.676067+00:00
2024-07-15T19:14:26.676089+00:00
1,251
false
# Code\n```\n# Write your MySQL query statement below\nSELECT \ncustomer_id\nFROM Customer\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)\n```
3
0
['MySQL']
0
customers-who-bought-all-products
Beat 97% ✅👉| Simple MySQL | Group by, Having, Distinct
beat-97-simple-mysql-group-by-having-dis-h6hu
Code\n\nselect customer_id from customer\ngroup by customer_id\nhaving count( distinct product_key) >= \n (select count(product_key) from product)\n
Kamal_Kumar123
NORMAL
2024-07-05T16:20:24.494517+00:00
2024-07-05T16:20:24.494549+00:00
1,664
false
# Code\n```\nselect customer_id from customer\ngroup by customer_id\nhaving count( distinct product_key) >= \n (select count(product_key) from product)\n```
3
0
['MySQL']
3
customers-who-bought-all-products
Simple, Easy and Fast MySQL Solution using sub-query
simple-easy-and-fast-mysql-solution-usin-qujb
Code\n\n# Write your MySQL query statement below\n\nSELECT c.customer_id\nFROM Customer c\ngroup by customer_id \nHAVING count(distinct c.product_key) = (select
pratyush2331
NORMAL
2023-11-10T09:52:53.419484+00:00
2023-11-10T09:52:53.419507+00:00
738
false
# Code\n```\n# Write your MySQL query statement below\n\nSELECT c.customer_id\nFROM Customer c\ngroup by customer_id \nHAVING count(distinct c.product_key) = (select count(distinct p.product_key) FROM Product p);\n\n```
3
0
['MySQL']
0
customers-who-bought-all-products
Find Customers Who Bought All Products in MySQL
find-customers-who-bought-all-products-i-vjsp
Intuition\n Describe your first thoughts on how to solve this problem. \nWe need to find customers who bought all the products in the given table.\n\n# Approach
samabdullaev
NORMAL
2023-10-23T13:24:29.232796+00:00
2023-10-23T13:24:29.232821+00:00
435
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to find customers who bought all the products in the given table.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Find the total number of distinct products in the `Product` table.\n\n > `SELECT` \u2192 This command retrieves data from a database\n\n > `COUNT()` \u2192 This function returns the number of rows\n\n > `DISTINCT` \u2192 This statement returns only distinct (different) values\n\n2. Filter the customers who have bought the same count of products as the total distinct products.\n\n > `HAVING` \u2192 This clause allows filtering of aggregated results produced by `GROUP BY` clause (`WHERE` keyword cannot be used with aggregate functions)\n\n3. Group the results by customer id to identify customers who bought all the products.\n\n > `GROUP BY` \u2192 This command groups rows that have the same values into summary rows, typically to perform aggregate functions on them\n\n# Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`n` is the number of rows in the table. This is because the query processes each row in the table once to find customers who bought all the products.\n\n# Code\n```\nSELECT customer_id \nFROM Customer\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (\n SELECT COUNT(DISTINCT product_key) \n FROM Product\n);\n```
3
0
['MySQL']
1
customers-who-bought-all-products
Easy approach using 'HAVING' | 'GROUP BY'
easy-approach-using-having-group-by-by-r-js4y
\n# Code\n\n/* Write your T-SQL query statement below */\n\nSELECT customer_id\nFROM Customer C \nGROUP BY customer_id\nHAVING count(DISTINCT C.product_key) = (
RishabhKumar23
NORMAL
2023-09-21T18:04:43.268699+00:00
2023-09-21T18:04:43.268728+00:00
1,273
false
\n# Code\n```\n/* Write your T-SQL query statement below */\n\nSELECT customer_id\nFROM Customer C \nGROUP BY customer_id\nHAVING count(DISTINCT C.product_key) = (SELECT count(product_key) FROM Product);\n```
3
0
['MS SQL Server']
1
customers-who-bought-all-products
MYSQL SOLUTION WITH COMPLETE EXPLANATION !!!!!!
mysql-solution-with-complete-explanation-1pno
Intuition\n Describe your first thoughts on how to solve this problem. \nThe query aims to find customer IDs who have purchased all the products from the Custom
hirentimbadiya74
NORMAL
2023-09-17T16:01:31.945853+00:00
2023-09-17T16:01:31.945885+00:00
483
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe query aims to find customer IDs who have purchased all the products from the Customer table. It does so by counting the distinct product keys purchased by each customer and comparing that count to the total number of products in the `Product` table.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. The inner subquery groups the customers by their IDs and counts the distinct product keys purchased by each customer using `COUNT(DISTINCT product_key)`.\n\n2. The `HAVING` clause filters out only those customers who have purchased as many distinct products as the total number of products in the `Product` table. This ensures that the customer has bought all the available products.\n\n3. The outer query selects the `customer_id` from the result of the inner subquery, which gives us the customer IDs who meet the criteria.\n\n\n# Complexity\n## Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- The time complexity of this query depends on the size of the `Customer` table and the `Product` table.\n\n- The inner subquery involves grouping and counting for each customer, which can be considered O(N), where N is the number of rows in the `Customer` table.\n- The subquery `(SELECT COUNT(*) FROM Product)` is a constant-time operation, as it calculates the total number of products, which doesn\'t depend on the size of the tables.\n\nSo, the overall time complexity is approximately **`O(N)`**, where N is the **number of customers**.\n\n## Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- The space complexity is primarily determined by the temporary result set created by the inner subquery. This result set stores the `customer_id` and the count of distinct product keys for each customer.\n\n- **Assuming M is the number of distinct customers who meet the criteria (those who have bought all products), the space complexity is `O(M)`**.\n\nIn terms of space complexity, it\'s essential to consider the size of the result set that needs to be stored in memory.\n\n# Code\n```\n# Write your MySQL query statement below\nSELECT customer_id \nFROM(\n SELECT customer_id , COUNT(DISTINCT product_key) AS cnt\n FROM Customer\n GROUP BY customer_id\n HAVING cnt = (SELECT COUNT(*) FROM Product)\n) Temp;\n```\n\n## Do Upvote if you got it! :)
3
0
['MySQL']
1
customers-who-bought-all-products
MySQL Solution for Customers who Brought All Products Problem
mysql-solution-for-customers-who-brought-g2zl
Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind the given solution is to find customer IDs that have purchased all
Aman_Raj_Sinha
NORMAL
2023-05-18T03:27:57.486622+00:00
2023-05-18T03:27:57.486654+00:00
3,906
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind the given solution is to find customer IDs that have purchased all distinct products available in the Product table. The approach involves grouping the Customer table by customer_id and then applying a condition in the HAVING clause to compare the sum of distinct product_key values for each customer with the total sum of product_key values in the Product table.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Group the rows in the Customer table by customer_id.\n1. For each group, calculate the sum of distinct product_key values.\n1. Compare the sum of distinct product_key values for each group with the total sum of product_key values in the Product table.\n1. Return the customer_id values that satisfy the condition.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this solution depends on the size of the Customer and Product tables. The grouping operation requires scanning the Customer table, which has a time complexity of O(n), where n is the number of rows in the Customer table. Additionally, calculating the sum of distinct product_key values involves aggregating and comparing values, which also has a time complexity of O(n).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of this solution depends on the number of distinct customer_id values and the number of distinct product_key values. The query requires storing the grouped customer_id values and the distinct product_key values temporarily, so the space complexity is determined by the cardinality of these values.\n\n# Code\n```\n# Write your MySQL query statement below\nselect customer_id from Customer group by customer_id\nhaving sum(distinct product_key) = \n(select sum(product_key) from Product)\n```
3
0
['MySQL']
2
customers-who-bought-all-products
Easy Solution
easy-solution-by-shwetas73-v2pi
\nselect customer_id\nfrom customer \ngroup by customer_id\nhaving count(distinct(product_key)) = (select count(product_key) from product)\n
shwetas73
NORMAL
2021-09-16T22:17:40.942070+00:00
2021-09-16T22:17:40.942118+00:00
380
false
```\nselect customer_id\nfrom customer \ngroup by customer_id\nhaving count(distinct(product_key)) = (select count(product_key) from product)\n```
3
0
[]
1
customers-who-bought-all-products
One subquery
one-subquery-by-lancexie-i63k
Select the customers who purchased the as many distinct product_key as the count of all product in product table \n\t\n\tselect customer_id\n from custome
lancexie
NORMAL
2021-02-26T01:34:05.402484+00:00
2021-02-26T01:34:05.402523+00:00
254
false
Select the customers who purchased the as many distinct product_key as the count of all product in product table \n\t\n\tselect customer_id\n from customer\n group by customer_id\n having count(distinct product_key) = (select count(*) from product);
3
0
[]
1
customers-who-bought-all-products
3 solutions (NOT EXISTS + EXCEPT, HAVING + COUNT()) work for all DBMS
3-solutions-not-exists-except-having-cou-kx5t
Code
DmCZxtEfdY
NORMAL
2025-04-07T15:11:17.793493+00:00
2025-04-07T15:11:17.793493+00:00
289
false
# Code ``` -- First solution: NOT EXISTS + EXCEPT select distinct customer_id from Customer C1 where not exists( select product_key from Product except select product_key from Customer C2 where C2.customer_id = C1.customer_id ) -- Second solution: NOT EXISTS (twice) select distinct customer_id from Customer C1 where not exists( select 1 from Product P where not exists ( select 1 from Customer C2 where C2.customer_id = C1.customer_id and C2.product_key = P.product_key) ) -- Third solution: HAVING + COUNT() select customer_id from Customer group by customer_id having count(distinct product_key) = (select count(*) from Product) ```
2
0
['MySQL', 'Oracle', 'MS SQL Server']
0
customers-who-bought-all-products
Use "having", "count" and "distinct" to get the answer | Easy to understand
use-having-count-and-distinct-to-get-the-iagk
Code
Ahrarhussain
NORMAL
2025-04-03T10:23:04.100902+00:00
2025-04-03T10:23:04.100902+00:00
408
false
# Code ```mysql [] # Write your MySQL query statement below Select c.customer_id From Customer c Group by c.customer_id Having count(DISTINCT c.product_key) = ( Select count(*) From Product ); ```
2
0
['Database', 'MySQL']
1
customers-who-bought-all-products
Very Easy Solution || SQL 🚀🤓
very-easy-solution-sql-by-uwwcpcfmx5-ozn4
PLEASE UPVOTE !!😁😫CodeIF YOU HAVE DOUBT FEEL FREE TO ASK AND COMMENT ME DOWN!!
UWWcPcfMx5
NORMAL
2025-03-26T05:34:36.203362+00:00
2025-03-26T05:34:36.203362+00:00
231
false
# PLEASE UPVOTE !!😁😫 ![647f77b9-8a52-41d1-9fde-104782a9fc5b_1685122990.4751306.png](https://assets.leetcode.com/users/images/e0bc00ab-9739-46e0-9d02-b1b3be363368_1742967197.4266446.png) # Code ```mysql [] # Write your MySQL query statement below SELECT customer_id FROM Customer Group by customer_id HAVING COUNT(distinct product_key) = (SELECT COUNT(product_key) FROM Product) ``` # IF YOU HAVE DOUBT FEEL FREE TO ASK AND COMMENT ME DOWN!!
2
0
['MySQL']
0
customers-who-bought-all-products
Simple Query ✅ | With Proper Explanation 🤝
simple-query-with-proper-explanation-by-ugqjt
IntuitionTo solve this problem, we need to determine which customers have bought all distinct products listed in the Product table.• First, count the number of
NadeemMohammed
NORMAL
2025-03-13T10:51:06.031097+00:00
2025-03-13T10:51:06.031097+00:00
350
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> To solve this problem, we need to determine which customers have bought all distinct products listed in the Product table. • First, count the number of distinct products available. • Then, for each customer_id, count the number of distinct products they have purchased. • If both counts match, that means the customer has purchased all products. # Approach <!-- Describe your approach to solving the problem. --> 1. Count the total number of distinct products available in the Product table **SELECT COUNT(DISTINCT product_key) FROM Product** • This gives the total number of unique products. 2. Group purchases by customer_id and count how many distinct products each customer has bought. • If a customer’s distinct product count equals the total count from step 1, that customer qualifies. 3. Use HAVING to filter customers who have purchased all products SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(DISTINCT product_key) FROM Product) • GROUP BY customer_id: Groups the purchases by customer. • COUNT(DISTINCT product_key): Counts the number of different products each customer has purchased. • HAVING: Filters out customers who haven’t bought all products. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> If you found my solution helpful, I’d really appreciate it if you could give it an upvote! 🙌 Your support keeps me motivated to share more simple and efficient solutions. Thank you! 😊 # Code ```postgresql [] -- Write your PostgreSQL query statement below SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(DISTINCT product_key) FROM Product) ```
2
0
['PostgreSQL']
0
customers-who-bought-all-products
Easy Solution 😊
easy-solution-by-vsonawane-h000
Code
vsonawane
NORMAL
2025-03-08T23:47:03.084944+00:00
2025-03-08T23:47:03.084944+00:00
492
false
# Code ```mysql [] # Write your MySQL query statement below select customer_id from customer group by customer_id having count(distinct product_key) = (select count(*)from product) ```
2
0
['MySQL']
0
customers-who-bought-all-products
Easy MySQL Solution | O(1) | With Explanation
easy-mysql-solution-o1-with-explanation-o507h
IntuitionTo find the customer who brought all the products, wee need to compare the distinct number of products bought by each customer from Customer table, mus
snehalmankar
NORMAL
2025-03-06T04:05:29.242022+00:00
2025-03-06T04:05:29.242022+00:00
457
false
# Intuition To find the customer who brought all the products, wee need to compare the distinct number of products bought by each customer from Customer table, must be equal to the distinct number of products present in the Products table. # Approach 1. Select the output as `customer_id` from Customer table. 2. Perform group by operation on `Customer` column. 3. As we are comparing using an `Aggregate function` the condition must be given in the `HAVING` clause. 4. Lastly compare with `Distinct` count of Products from `Product` table. # Complexity - Time complexity: **O(n+m)** for n=number of customers from `Customer` table and m=number of products from `Product` table. - Space complexity: **O(1)** because no additional space required. # Code ```mysql [] # Write your MySQL query statement below SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(DISTINCT product_key) FROM Product); ```
2
0
['MySQL']
0
customers-who-bought-all-products
4 LINE 🌟 || Mysql 🪐
4-line-mysql-by-galani_jenis-et7y
Code
Galani_jenis
NORMAL
2025-01-31T10:10:06.418126+00:00
2025-01-31T10:10:06.418126+00:00
542
false
# Code ```mysql [] # Write your MySQL query statement below SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product); ```
2
0
['MySQL']
0
customers-who-bought-all-products
Simple & Best Solution, Easy To Understand
simple-best-solution-easy-to-understand-7vwkg
IntuitionThe problem is to identify which customers purchased all the products listed in the Product table. A customer is considered to have bought all products
aaka-nksha1
NORMAL
2025-01-24T16:52:55.357623+00:00
2025-01-24T16:52:55.357623+00:00
761
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem is to identify which customers purchased all the products listed in the Product table. A customer is considered to have bought all products if, for that customer, the number of distinct products they bought matches the total number of products available in the Product table. The goal is achieved by: - Counting how many unique products each customer has bought. - Comparing that count to the total number of products in the Product table. - Returning the customer IDs where the counts match. # Approach <!-- Describe your approach to solving the problem. --> - Count Products per Customer: Group the Customer table by customer_id and count the distinct product_key each customer purchased. - Get Total Products: Use a subquery to count the total number of products in the Product table. - Filter Customers: Use a HAVING clause to compare the count of distinct products per customer with the total product count. Only customers who bought all products are selected. - Return Results: Output the customer_id of customers meeting the condition. # Complexity - Time complexity: O(n+m) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(k) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```mysql [] # Write your MySQL query statement below SELECT customer_id FROM Customer GROUP BY 1 HAVING COUNT(DISTINCT product_key) = ( SELECT COUNT(*) FROM Product ); ```
2
0
['Math', 'Database', 'MySQL']
0
customers-who-bought-all-products
You🤓 it is so Easy(AASAN HAI?) | Oracle | MySQL | Postgre |
you-it-is-so-easyaasan-hai-oracle-mysql-71ysi
ApproachUSING With clause:-WITH CTEName AS ( SELECT ... -- Query that creates the temporary result set ) SELECT ... FROM CTEName WHERE ...;AlternateNoteBe aware
SahilDevli1
NORMAL
2025-01-17T17:00:04.663038+00:00
2025-01-17T17:00:04.663038+00:00
233
false
# Approach USING With clause:- WITH CTEName AS ( SELECT ... -- Query that creates the temporary result set ) SELECT ... FROM CTEName WHERE ...; # Alternate -- for all : OracleSQL | MySQL | PostgreSQL SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(DISTINCT product_key) FROM Product); ``` ``` # Note Be aware of using 'DISTINCT' COUNT(DISTINCT product_key): Ensures that we only count unique product purchases per customer and properly handles cases where some rows might have NULL values. # Code ```OracleSQL [] /* Write your PL/SQL query statement below */ WITH TotalProducts AS ( SELECT COUNT(DISTINCT product_key) AS total_product_count FROM Product ) SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT total_product_count FROM TotalProducts); ``` ```MySQL [] WITH TotalProducts AS ( SELECT COUNT(DISTINCT product_key) AS total_product_count FROM Product ) SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT total_product_count FROM TotalProducts); ``` ``` PostgreSQL [] WITH TotalProducts AS ( SELECT COUNT(DISTINCT product_key) AS total_product_count FROM Product ) SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT total_product_count FROM TotalProducts); ``` # do Upvote 👨🏾 it will help me to feed my cat🐱 hope it will help🫂 https://leetcode.com/list/o2qifkts
2
0
['MySQL', 'Oracle', 'PostgreSQL']
0
customers-who-bought-all-products
👉🏻FAST AND EASY TO UNDERSTAND SOLUTION || MySQL
fast-and-easy-to-understand-solution-mys-hnzn
IntuitionApproachComplexity Time complexity: Space complexity: Code
djain7700
NORMAL
2025-01-08T18:05:33.251413+00:00
2025-01-08T18:05:33.251413+00:00
217
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 ```mysql [] # Write your MySQL query statement below WITH cte AS (SELECT *, COUNT(DISTINCT product_key) as cnt FROM Customer GROUP BY customer_id) SELECT customer_id FROM cte WHERE cnt = (SELECT COUNT(*) FROM Product) ```
2
0
['Database', 'MySQL']
0
customers-who-bought-all-products
The idea is using the " Count " clause
the-idea-is-using-the-count-clause-by-ch-4mo4
\n\n# Code\nmysql []\n# Write your MySQL query statement below\nSELECT customer_id \nFROM Customer \nGROUP BY customer_id \nHAVING COUNT(DISTINCT product_Key) =
chahiri_abderrahmane
NORMAL
2024-10-27T22:51:12.707416+00:00
2024-10-27T22:51:12.707438+00:00
393
false
\n\n# Code\n```mysql []\n# Write your MySQL query statement below\nSELECT customer_id \nFROM Customer \nGROUP BY customer_id \nHAVING COUNT(DISTINCT product_Key) = ( SELECT COUNT(product_Key) FROM Product);\n```
2
0
['MySQL']
1
customers-who-bought-all-products
Easy Query using JOINS and GROUP BY
easy-query-using-joins-and-group-by-by-u-77om
Code\npostgresql []\n-- Write your PostgreSQL query statement below\nselect customer_id from Customer c \njoin Product p on c.product_key = p.product_key\ngroup
underdog13
NORMAL
2024-09-28T12:27:34.424611+00:00
2024-09-28T12:27:34.424655+00:00
140
false
# Code\n```postgresql []\n-- Write your PostgreSQL query statement below\nselect customer_id from Customer c \njoin Product p on c.product_key = p.product_key\ngroup by c.customer_id\nhaving count(distinct c.product_key) = (select count(*) from Product)\n```\n![9c6f9412-c860-47d6-9a2e-7fcf37ff3321_1686334926.180891.png](https://assets.leetcode.com/users/images/934e2681-0e03-465b-9507-f78fdb46cd8a_1727526442.9289637.png)\n
2
0
['PostgreSQL']
2
customers-who-bought-all-products
MS SQL Solution. Beats 88.85%. Group by + having
ms-sql-solution-beats-8885-group-by-havi-361k
Code\n\n/* Write your T-SQL query statement below */\nselect customer_id from Customer\ngroup by customer_id\nhaving count(distinct product_key) = (select count
Kristina_m
NORMAL
2024-07-23T14:25:26.105993+00:00
2024-07-23T14:28:38.583137+00:00
848
false
# Code\n```\n/* Write your T-SQL query statement below */\nselect customer_id from Customer\ngroup by customer_id\nhaving count(distinct product_key) = (select count(product_key) from Product)\n```\n\n![telegram-cloud-photo-size-2-5260650294499465606-y.jpg](https://assets.leetcode.com/users/images/51bffdf2-96a1-49ca-9a3b-93d2488ad8e3_1721744911.876846.jpeg)\n\n
2
0
['MS SQL Server']
0
customers-who-bought-all-products
Postgres
postgres-by-taimoor84656-cnbu
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
taimoor84656
NORMAL
2024-06-12T21:11:50.964333+00:00
2024-06-12T21:11:50.964352+00:00
569
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```\n-- Write your PostgreSQL query statement below\nselect customer_id\nfrom customer\ngroup by customer_id\nhaving count(distinct(product_key))=(select count(distinct(product_key)) from Product)\n```
2
0
['PostgreSQL']
1
customers-who-bought-all-products
One line solution.
one-line-solution-by-deleted_user-1fpo
Code\n\n# Write your MySQL query statement below\nSELECT customer_id FROM Customer GROUP BY customer_id\nHAVING COUNT(distinct product_key) = (SELECT COUNT(pro
deleted_user
NORMAL
2024-06-10T11:44:01.624916+00:00
2024-06-10T11:44:01.624946+00:00
405
false
# Code\n```\n# Write your MySQL query statement below\nSELECT customer_id FROM Customer GROUP BY customer_id\nHAVING COUNT(distinct product_key) = (SELECT COUNT(product_key) FROM Product)\n```
2
0
['MySQL']
0
customers-who-bought-all-products
Simple Approach
simple-approach-by-khalisulakbar-k615
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
khalisulakbar
NORMAL
2024-05-10T00:22:38.946384+00:00
2024-05-10T00:22:38.946418+00:00
569
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```\n-- Write your PostgreSQL query statement below\nSELECT\n customer_id\nFROM\n customer\nGROUP BY customer_id\nHAVING\n COUNT(DISTINCT product_key) = (SELECT COUNT(DISTINCT product_key) FROM product)\n```
2
0
['PostgreSQL']
1
customers-who-bought-all-products
Do NOT include DICTINCT in HAVING!
do-not-include-dictinct-in-having-by-kev-4nks
I see a lot of solution where you use DISTINCT in HAVING clause to filter out customers whose distinct product counts does not match the total unique product co
kevinmos
NORMAL
2024-05-08T17:58:30.692802+00:00
2024-05-08T17:58:30.692843+00:00
438
false
I see a lot of solution where you use DISTINCT in HAVING clause to filter out customers whose distinct product counts does not match the total unique product count. MySQL server let you pass but that is the logic bug of the compiler.\n**Wrong Solution:**\n```\nSELECT customer_id\nFROM Customer\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product);\n```\nThe funtamental flaw of such solution is that one should never include a DISTINCT within HAVING clause since HAVING only processes in terms of groups and has no idea about unique values within a certain group, LET ALONE you see that ```product_key``` is included in HAVING, which is does not exist in GROUP BY clause.\n\nPer SQL Documentation (https://www.ibm.com/docs/en/informix-servers/12.10?topic=statement-having-clause):\n```The condition in the HAVING clause cannot include a DISTINCT or UNIQUE aggregate expression```\n\nYou should NEVER:\n```\n1. include DISTINCT or UNIQUE in HAVING clause\n2. include attributes in HAVING clause that are not presented in GROUP BY clause\n```\n\n\n**Correct Solution:**\n```\n# get unique product counts\nWITH UniqueProductCount AS (\n SELECT COUNT(*) AS ct\n FROM Product\n), \n# get unique purchases from customers\nUniquePurchases AS (\n SELECT DISTINCT C.customer_id, C.product_key\n FROM Customer AS C\n), \n# get unique purchase counts for customers\nProductCount AS (\n SELECT UP.customer_id, COUNT(*) AS ct\n FROM UniquePurchases AS UP\n GROUP BY UP.customer_id\n)\n\n# select customers whose unique purchased products equal to unique product counts\nSELECT PC.customer_id\nFROM ProductCount AS PC, UniqueProductCount AS UPC\nWHERE PC.ct = UPC.ct\n```\n
2
0
[]
2