question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maximum-xor-for-each-query | Maximum XOR for Each Query Solution in C++ | maximum-xor-for-each-query-solution-in-c-nev7 | 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 | The_Kunal_Singh | NORMAL | 2023-04-24T13:54:46.245543+00:00 | 2023-04-27T16:24:51.379989+00:00 | 142 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution {\npublic:\n vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n int i, j=0, max;\n vector<int> ans;\n\n ans.push_back(nums[0]);\n for(i=1 ; i<nums.size() ; i++)\n {\n ans.push_back(ans[i-1]^nums[i]);\n }\n max = pow(2,maximumBit)-1;\n ans[ans.size()-1] = ans[ans.size()-1]^max;\n\n for(i=ans.size()-2 ; i>=0 ; i--)\n {\n ans[i] = ans[i]^max;\n }\n reverse(ans.begin(), ans.end());\n return ans;\n }\n};\n```\n\n | 2 | 0 | ['C++'] | 0 |
maximum-xor-for-each-query | ONE-PASS || C++ || TIME (n),SPACE(1) || SHORT & SWEET || EASY TO UNDERSTAND | one-pass-c-time-nspace1-short-sweet-easy-ts13 | \nclass Solution {\npublic:\n vector<int> getMaximumXor(vector<int>& nums, int k) {\n int x = (1L<<k)-1,y=0;\n for(auto &i: nums){\n | yash___sharma_ | NORMAL | 2023-03-28T12:49:04.517574+00:00 | 2023-03-28T12:49:04.517620+00:00 | 1,182 | false | ````\nclass Solution {\npublic:\n vector<int> getMaximumXor(vector<int>& nums, int k) {\n int x = (1L<<k)-1,y=0;\n for(auto &i: nums){\n y ^= i;\n }\n int a = y;\n for(int i = nums.size()-1; i>=0;i--){\n a = nums[i];\n nums[i]=(x^y);\n y ^= a;\n }\n reverse(nums.begin(),nums.end());\n return nums;\n }\n};\n```` | 2 | 0 | ['Bit Manipulation', 'C', 'Prefix Sum', 'C++'] | 2 |
maximum-xor-for-each-query | Simple O(n) solution || beats others | simple-on-solution-beats-others-by-shris-js38 | 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 | Shristha | NORMAL | 2023-01-18T09:52:52.850224+00:00 | 2023-01-18T09:52:52.850268+00:00 | 341 | 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 vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n //idea to to take xor of all elements in one paas with 2^maximumBit-1\n //arr[i]^arr[i+1]^...k=maximum\n //k=arr[i]^arr[i+1]^..^maximum(maximum=pow(2,maxbits)-1)\n int x_or=0;\n for(int i=0;i<nums.size();i++){\n x_or=x_or^nums[i];\n }\n int k=pow(2,maximumBit)-1;\n vector<int>res;\n for(int i=nums.size()-1;i>=0;i--){\n res.push_back(x_or^k);\n x_or=x_or^nums[i];\n }\n return res;\n \n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
maximum-xor-for-each-query | Easiest 😎 FAANG Method Ever !!! 💥 | easiest-faang-method-ever-by-adityabhate-rqug | \n\n# \uD83D\uDDEF\uFE0FComplexity :-\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 complexi | AdityaBhate | NORMAL | 2022-12-02T15:46:57.905537+00:00 | 2022-12-02T15:46:57.905566+00:00 | 403 | false | \n\n# \uD83D\uDDEF\uFE0FComplexity :-\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# \uD83D\uDDEF\uFE0FCode :-\n```\nclass Solution {\npublic:\n vector<int> getMaximumXor(vector<int>& n, int maximumBit) {\n vector<int> res(n.size());\n int val = (1 << maximumBit) - 1;\n for (int i = 0; i < n.size(); ++i)\n res[n.size() - i - 1] = val ^= n[i];\n return res;\n }\n};\n``` | 2 | 5 | ['Array', 'Bit Manipulation', 'Prefix Sum', 'C++', 'Java'] | 0 |
maximum-xor-for-each-query | Solution in O(N) | solution-in-on-by-sawantadesh09-2174 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nusing "k" (k < 2^maxnum | sawantadesh09 | NORMAL | 2022-11-05T11:41:24.450331+00:00 | 2022-11-05T11:41:24.450386+00:00 | 116 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nusing "k" (k < 2^maxnumBit) we can only set the last "maxnumBits" to maximize the number. So we can use mask in which all "maxnumBits" are set.And doing XOR with the mask gives the value of k which maximize the result.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n# Code\n```\nclass Solution {\npublic:\n vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n int mask = (1<<maximumBit)-1;\n vector<int> ans(nums.size());\n int i=0,j=nums.size()-1;\n int val = 0;\n while(j>=0)\n {\n val = val^nums[i];\n ans[j] = val^mask;\n i++;\n j--;\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Bit Manipulation', 'C++'] | 0 |
maximum-xor-for-each-query | Simple solution beats 99% | simple-solution-beats-99-by-mencibi-daje | Code\n\nclass Solution:\n def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:\n ans = [0] * len(nums)\n x = (2**maximumBit- | Mencibi | NORMAL | 2022-11-02T17:04:10.721865+00:00 | 2022-11-02T17:04:10.721890+00:00 | 343 | false | # Code\n```\nclass Solution:\n def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:\n ans = [0] * len(nums)\n x = (2**maximumBit-1)\n for i, n in enumerate(nums):\n x = x ^ n\n ans[-1-i] = x\n return ans \n``` | 2 | 0 | ['Python3'] | 1 |
maximum-xor-for-each-query | python | easy to understand (with explaination) | python-easy-to-understand-with-explainat-4yx3 | \nclass Solution:\n """\n approach: create a prefix array of XORs\n we know no cannot exceed 2^maximum_bit threfore the XOR cannot exceed 2^maximum_bit | rktayal | NORMAL | 2022-04-23T03:53:15.816380+00:00 | 2022-04-23T03:53:15.816412+00:00 | 169 | false | ```\nclass Solution:\n """\n approach: create a prefix array of XORs\n we know no cannot exceed 2^maximum_bit threfore the XOR cannot exceed 2^maximum_bit\n also, \n given maximum_bit as 3, \n number = 1 -> 001 XORING with 110 = 6 will give max of 7\n number = 2 -> 010 XORING with 101 = 5 will give max of 7 \n number = 3 -> 011 XORING with 100 = 4 will give max of 7\n number = 4 -> 100 XORING with 011 = 3 will give max of 7\n number = 5 -> 101 XORING with 010 = 2 will give max of 7\n number = 6 -> 110 XORING with 001 = 1 will give max of 7\n number = 7 -> 111 XORING with 000 = 0 will give max of 7\n \n hence, if XOR of numbers is x, we can XOR it with (2^maximum_bit - x) to get maximum result\n """\n def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:\n result = []\n xor_so_far = 0\n for i in range(len(nums)):\n xor_so_far ^= nums[i]\n # k = (2**maximum_bit - 1) - xor_so_far\n result.append((2 ** maximumBit - 1) - xor_so_far)\n return result[::-1]\n``` | 2 | 0 | ['Python'] | 1 |
maximum-xor-for-each-query | Easy Python Solution | Prefix Sum Technique | easy-python-solution-prefix-sum-techniqu-nziv | \nclass Solution:\n def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:\n pre=[0]*len(nums) #pre list of size nums \ | arpit_yadav | NORMAL | 2022-03-26T18:07:59.132596+00:00 | 2022-03-26T18:07:59.132638+00:00 | 230 | false | ```\nclass Solution:\n def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:\n pre=[0]*len(nums) #pre list of size nums \n pre[0]=nums[0]\n for i in range(1,len(nums)):\n pre[i]=pre[i-1]^nums[i] #Pre-Calculating the Xor Values of the nums list using Prefix Sum Technique \n k=(2**maximumBit)-1 #As the the maximum possible XOR result is always 2^(maximumBit) - 1\n for i in range(0,len(pre)):\n pre[i]=pre[i]^k #Doing Xor of k with pre calculated Xor values of list nums\n return pre[::-1] #Reverse the list to match the output\n``` | 2 | 0 | ['Prefix Sum', 'Python'] | 2 |
maximum-xor-for-each-query | Java Solution (2 ms, faster than 100.00% ) | java-solution-2-ms-faster-than-10000-by-f804k | Runtime: 2 ms, faster than 100.00% of Java online submissions.\nMemory Usage: 54.6 MB, less than 90.46% of Java online submissions.\n\nclass Solution {\n pub | Madhav1301 | NORMAL | 2021-10-05T04:06:29.757697+00:00 | 2021-10-05T04:21:54.509450+00:00 | 169 | false | **Runtime: 2 ms, faster than 100.00% of Java online submissions.\nMemory Usage: 54.6 MB, less than 90.46% of Java online submissions.**\n```\nclass Solution {\n public int[] getMaximumXor(int[] nums, int maximumBit) {\n for(int i=1; i<nums.length; i++)\n nums[i] ^= nums[i-1];\n \n int k = (int)Math.pow(2, maximumBit)-1;\n \n int[] res = new int[nums.length]; \n int index = 0;\n for(int i=nums.length-1; i>=0; i--){ \n res[index] = nums[i] ^ k;\n index++;\n }\n return res;\n }\n}\n``` | 2 | 0 | ['Bit Manipulation', 'Java'] | 0 |
maximum-xor-for-each-query | Easy Solution c++ | easy-solution-c-by-adikajale_123-kmyb | class Solution {\npublic:\n\tvector getMaximumXor(vector& nums, int maximumBit) {\n\t\tint xorOfArray = 0;\n\t\tfor (auto x : nums) {\n\t\t\txorOfArray ^= x;\n\ | adikajale_123 | NORMAL | 2021-07-26T10:42:12.671986+00:00 | 2021-07-26T10:42:12.672013+00:00 | 74 | false | class Solution {\npublic:\n\tvector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n\t\tint xorOfArray = 0;\n\t\tfor (auto x : nums) {\n\t\t\txorOfArray ^= x;\n\t\t}\n\t\tvector<int> ans;\n\t\tint bits = (2 << (maximumBit - 1)) - 1;\n\t\tfor (int i = nums.size() - 1; i >= 0; i--) {\n\t\t\txorOfArray ^= bits;\n\t\t\tans.push_back(xorOfArray);\n\t\t\txorOfArray ^= bits;\n\t\t\txorOfArray ^= nums[i];\n\t\t}\n\t\treturn ans;\n\t}\n}; | 2 | 0 | [] | 0 |
maximum-xor-for-each-query | Bit Manipulation combined with DP | O(n) Python Solution with Explanation | bit-manipulation-combined-with-dp-on-pyt-8uck | We must be aware of the fact that the maximum possible number we get after XORing the list elements will always be 2^maximumBit - 1 .\nIt has been also mentione | spandan09 | NORMAL | 2021-06-16T11:58:30.944010+00:00 | 2021-06-16T11:58:30.944056+00:00 | 94 | false | We must be aware of the fact that the maximum possible number we get after XORing the list elements will always be `2^maximumBit - 1 ` .\nIt has been also mentioned in the constraints that `0 <= nums[i] < 2maximumBit`\n\nIf you want a detailed explanation of it is so then I would highly recommend to go check this [link](https://leetcode.com/problems/maximum-xor-for-each-query/discuss/1163057/Easy-O(N)-Solution-w-Explanation-or-Max-XOR-2maximumBit-1) where @archit91 has explained the whole thing in a very understandable way.\n\n**How to get the desired number which would maximize the entire XORed item**\n\nFor that let\'s look at a simple example to understand how XOR works - \n\nif `a XOR b = c` then `a = c XOR B` and `b = c XOR a `\n\nThis shows us that the reverse of XOR is XOR itself.\n\nSince ` list_elements XOR unknown_number = maximized_number`\nTherefore `unknown_number = maximized_number XOR list_elements`\n\n**Solving the question using DP approach**\n\nTaking the example given in the question itself \n\nInput: ` nums = [2,3,4,7], maximumBit = 3`\n\nExplanation: The queries are answered as follows:\n1st query: `nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7`.\n2nd query: `nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7`.\n3rd query: `nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7`.\n4th query: `nums = [2], k = 5 since 2 XOR 5 = 7`.\n\nOutput:` [5,2,6,5]`\n\n\nLet us assume dp to be our resulting list.\nNow, \n\nlast element of resulting list = first element of given list XOR `2^maximumBit - 1 `\ni.e. `dp[-1] = nums[0] XOR 2^maximumBit - 1 `\n\n2nd last element of resulting list = last element of resulting list XOR 2nd element of given list\ni.e. `dp[-2] = dp[-1] XOR nums[1]`\n\nsimilarly 3rd last element of resulting list = 2nd last element of resulting list XOR 3rd element of given list\ni.e. `dp[-3] = dp[-2] XOR nums[2]`\n.\n.\n.\n.\nand so on\n\nBy observing the pattern we can derive the formula for DP approach as:\n`dp[-i] = dp[-i + 1] XOR nums[-i + 1]` for i from 2 -> (length of nums + 1)\n\n\n**Final Solution**\n\n**Python**\n\n```\nclass Solution:\n def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:\n \n length = len(nums)\n maximum = 2 ** maximumBit - 1\n \n dp = [0] * length\n dp[-1] = nums[0] ^ maximum\n \n for i in range(2, length+1):\n dp[-i] = dp[-i + 1] ^ nums[-i + 1]\n \n return dp\n```\n\n\n**Time Complexity:** O(n) \n**Space Complexity:** O(n)\n*where n is the length of the given list.* | 2 | 0 | [] | 0 |
maximum-xor-for-each-query | C++ Simple Solution using Prefix XOR | c-simple-solution-using-prefix-xor-by-ch-edaq | \nclass Solution {\npublic:\n vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n vector<int>xorr;\n int XORR = 0;\n\t\t\n | chirags_30 | NORMAL | 2021-05-23T19:57:07.207067+00:00 | 2021-05-23T19:57:07.207106+00:00 | 141 | false | ```\nclass Solution {\npublic:\n vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n vector<int>xorr;\n int XORR = 0;\n\t\t\n for(auto n:nums)\n {\n XORR ^= n;\n xorr.push_back(XORR);\n }\n vector<int> ans;\n int max = pow(2, maximumBit) - 1;\n \n for(int i=xorr.size()-1; i>=0; i--)\n ans.push_back(xorr[i]^max);\n\t\t\t\n return ans;\n }\n};\n``` | 2 | 0 | ['C', 'C++'] | 0 |
maximum-xor-for-each-query | [C++] Simple solution O(N) | c-simple-solution-on-by-millenniumdart09-uxnd | C++:\n\nclass Solution {\npublic:\n \n int solve(int X,int k)\n {\n int number_of_bits = k;\n return ((1 << number_of_bits) - 1) ^ X;\n | millenniumdart09 | NORMAL | 2021-04-18T10:55:28.024618+00:00 | 2021-04-18T12:09:04.444541+00:00 | 123 | false | **C++:**\n```\nclass Solution {\npublic:\n \n int solve(int X,int k)\n {\n int number_of_bits = k;\n return ((1 << number_of_bits) - 1) ^ X;\n }\n \n vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n vector<int>ans;\n int n=nums.size();\n int dp[n];\n dp[0]=nums[0];\n for(int i=1;i<n;i++)\n {\n dp[i]=dp[i-1]^nums[i];\n }\n for(int i=0;i<n;i++)\n {\n int res=solve(dp[n-i-1],maximumBit);\n ans.push_back(res);\n }\n \n \n return ans;\n }\n};\n```\n | 2 | 1 | ['Dynamic Programming', 'Bit Manipulation', 'C'] | 0 |
maximum-xor-for-each-query | C++/ 8 line Code | c-8-line-code-by-adg1822-oe0l | The idea is here to use XOR property if C= A^B then B = A^C , A^A = 0 and 0^A=A.\nMy approach:\n1st calculate XOR of whole array nums .\n1. Maximum output we c | adg1822 | NORMAL | 2021-04-17T18:51:44.223128+00:00 | 2021-04-19T09:02:00.524920+00:00 | 82 | false | The idea is here to use `XOR` property if ``C= A^B`` then ``B = A^C`` , `A^A = 0` and `0^A=A`.\nMy approach:\n1st calculate XOR of whole array `nums` .\n1. Maximum output we can expect will be `pow(2,n-1)-1` so store it in variable `y`\n2. Since we want `k` which give us max `y` and `y = full_xor^k` so `k` will be equal to `full_xor^y`.\n\nNow start from end and calculate `k` which provide max `y` using my approach point 2 and update `full_xor` to remove that element from `full_xor` by updating `full_xor = full_xor ^ nums[i]` this will remove `nums[i]` from `full_xor` by property `A^B^B=A`.\n\n```\nclass Solution {\npublic:\n vector<int> getMaximumXor(vector<int>& nums, int mb) {\n int i,j,n=nums.size(),full_xor=0,y=pow(2,mb)-1;\n for(auto x:nums)full_xor=full_xor^x;\n vector<int>ans;\n for(i=n-1;i>=0;--i){\n ans.push_back(full_xor^y);\n full_xor=full_xor^nums[i];\n }\n return ans;\n }\n};\n``` | 2 | 1 | [] | 0 |
maximum-xor-for-each-query | JAVA Beginner Friendly | java-beginner-friendly-by-himanshuchhika-9aqw | EXPLANATIONS:\n Before moving to solution let me share a xor property with you which we are going to use in this question : \n if A^B=C then A^C=B\n A^B^A = B\n | himanshuchhikara | NORMAL | 2021-04-17T16:34:19.470214+00:00 | 2021-04-17T16:50:00.314908+00:00 | 128 | false | **EXPLANATIONS:**\n Before moving to solution let me share a xor property with you which we are going to use in this question : \n* ` if A^B=C then A^C=B`\n* `A^B^A = B`\n\nwe can find maximum through maximumBit.\n we have to find k , \n xor ^ k = max \n k=xor^max\n \n and then update the xor exclude last index value using second property.\n**CODE:**\n```\n public int[] getMaximumXor(int[] nums, int maximumBit) {\n \n int max=(int)Math.pow(2,maximumBit)-1;\n \n int[] result=new int[nums.length];\n \n int xor=0;\n for(int num:nums) xor^=num;\n \n for(int i=0;i<nums.length;i++){\n result[i]=(xor^max);\n xor^=nums[nums.length-1-i];\n }\n return result;\n }\n```\n\n**Complexity:**\n`Time:O(n) and Space:O(n)`\n\nPlease **UPVOTE** if found it helpful and feel free to reach out to me or comment down if you have any doubt. | 2 | 1 | ['Bit Manipulation', 'Java'] | 1 |
maximum-xor-for-each-query | Python 3, Simple 5 lines | python-3-simple-5-lines-by-silvia42-w8ta | nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k is maximized\nnums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k = 2**maximumBit-1=\'111..11\'b | silvia42 | NORMAL | 2021-04-17T16:12:45.312545+00:00 | 2021-04-17T16:12:45.312573+00:00 | 236 | false | ```nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k``` is maximized\n```nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k = 2**maximumBit-1=\'111..11\'```binary\nWe are precounting ```numsXOR``` array, where we have \n```numsXOR[i]=nums[0] XOR nums[1] XOR ... XOR nums[i]```\nWe need to find ```y```\n```numsXOR[i] XOR y = 2**maximumBit-1```\nWhich is: ```y = numsXOR[i] XOR 2**maximumBit-1```\n\n```\nclass Solution:\n def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:\n z=2**maximumBit-1\n numsXOR=[nums[0]]\n for x in nums[1:]:\n numsXOR.append(numsXOR[-1]^x)\n return [x^z for x in numsXOR[::-1]]\n```\nTime complexity is O(n).\nSpace complexity is O(n). | 2 | 0 | [] | 1 |
maximum-xor-for-each-query | C++ | Using Stack | | c-using-stack-by-deleted_user-z4bc | \nclass Solution {\npublic:\n vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n int k = pow(2,maximumBit)-1;\n stack<int>aux;\n | deleted_user | NORMAL | 2021-04-17T16:05:45.212361+00:00 | 2021-04-17T16:05:45.212403+00:00 | 126 | false | ```\nclass Solution {\npublic:\n vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n int k = pow(2,maximumBit)-1;\n stack<int>aux;\n int x=0;\n for(int i=0;i<nums.size();i++)\n {\n x = (x^nums[i]);\n aux.push(x);\n }\n vector<int>res;\n while(!aux.empty())\n {\n res.push_back(aux.top()^k);\n aux.pop();\n }\n return res;\n }\n};\n``` | 2 | 0 | [] | 2 |
maximum-xor-for-each-query | Maximum XOR for each query - O(N) solution in JAVA. | maximum-xor-for-each-query-on-solution-i-1n41 | A few observations that need to be enlisted :-\n\n For each subsequent query i, the elements from the range [0, n-i-1] need to be taken into account, for 0\u226 | user3203t | NORMAL | 2021-04-17T16:02:33.325396+00:00 | 2021-04-17T18:35:23.533071+00:00 | 200 | false | A few observations that need to be enlisted :-\n\n* For each subsequent query *i*, the elements from the range [0, *n*-*i*-1] need to be taken into account, for *0\u2264i\u2264n-1*, i.e, result[0] is some function on *nums[0...n-1]*, and so on.\n* The task is to evaluate XOR of all elements in the specified range of nums[ ].\n* To obtain maximum XOR with a certain K < 2<sup>*maximumBit*</sup>, K should be such that when XOR-ed with an obtained value, the result should have all set bits, i.e, numbers like, 1, 11, 111, 1111 and so on depending on the value of *maximumBit*. If the *maximumBit* is say M, the maximum XOR value obtained would always be 1111....*M* times.\n\nImplementation procedures :-\n\n* Precalculation of all XOR values in the array would prevent us from calculating xor values multiple times. Let\'s consider an array xor[ ], where xor[i] = XOR(nums[0...i]), (XOR of all values from index 0 to i in nums, with *0\u2264i\u2264n-1*)\n* The numbers 1, 11, 111 etc are of the type 2<sup>*maximumBit*</sup> - 1. Let\'s call this our mask. \n* Thus, *mask = (1 << maximumBit) - 1*. \n* A property of XOR that comes handy is, ***If A XOR B = C then, A XOR C = B and B XOR C = A***. Therefore, if a number **Z XOR K = mask, then Z XOR mask = K**\n\nThis outlines the basic intuition and implementation required for the problem.\n\n```\npublic int[] getMaximumXor(int[] arr, int M) {\n int res[] = new int[arr.length]; //result array\n for(int i = 1; i < arr.length; i++)\n arr[i] ^= arr[i-1]; //Using the same array for XOR value precalculation\n int index = 0, mask;\n for(int i = arr.length - 1; i >= 0; i--) {\n mask = (1 << M) - 1; //2 raised to the power M minus 1\n res[index++] = (mask ^ arr[i]);\n }\n return res;\n }\n```\t\n\t\nTime Complexity: O(*N*), *N* is the array length.\nSpace Complexity : O(1) (excluding the result array) | 2 | 0 | ['Bit Manipulation', 'Bitmask', 'Java'] | 0 |
maximum-xor-for-each-query | [C++] DP || Easy and Clean || O(n) | c-dp-easy-and-clean-on-by-_a_man-opdk | \nclass Solution {\npublic:\n vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n int len = nums.size();\n vector<int> dp(len, 0); | _A_Man | NORMAL | 2021-04-17T16:01:30.043337+00:00 | 2021-04-17T20:35:22.175474+00:00 | 184 | false | ```\nclass Solution {\npublic:\n vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n int len = nums.size();\n vector<int> dp(len, 0);\n vector<int> ans;\n \n dp[0] = nums[0];\n \n int maxx = pow(2, maximumBit) - 1; // maxx = maximum possible k\n int temp = maxx ^ nums[0]; // If a^b = c, then a = c^b and b = c^a\n ans.push_back(temp);\n \n for(int i = 1; i<len; i++){\n dp[i] = dp[i-1] ^ nums[i];\n temp = maxx ^ dp[i];\n ans.push_back(temp);\n }\n \n reverse(ans.begin(), ans.end());\n return ans;\n }\n};\n``` | 2 | 1 | ['Dynamic Programming', 'C', 'C++'] | 1 |
maximum-xor-for-each-query | Solved Using Trie – Not the Most Optimized, But It Works!.. | solved-using-trie-not-the-most-optimized-5iqo | IntuitionThe problem requires us to compute the maximum possible XOR value for each prefix of the given array. XOR operations have a unique property: flipping b | Utkarsh_bhandari | NORMAL | 2025-03-27T16:38:47.775594+00:00 | 2025-03-27T16:38:47.775594+00:00 | 9 | false | 
# Intuition
The problem requires us to compute the maximum possible XOR value for each prefix of the given array. XOR operations have a unique property: flipping bits maximizes the result.
To efficiently find the best possible XOR value for a given number, we use a **Trie (prefix tree)**, which allows quick lookups and modifications.
The goal is to:
1. Maintain a **Trie** that stores binary representations of numbers from `0` to `2^maximumBit - 1`.
2. Calculate the cumulative XOR of the array.
3. For each prefix, find the number `k` such that `XOR ⊕ k` is maximized using the Trie.
---
here, ⊕ = ^
# Approach
### Step 1: **Understanding the Maximum XOR Concept**
- XOR of two numbers is maximized when their bits differ as much as possible.
- For example, `5 (101)` and `2 (010)`, `5 ⊕ 2 = 7 (111)`, which is the highest possible XOR result between them.
- To find the best possible XOR value for a number, we check the Trie for a number with opposite bits.
---
### Step 2: **Building the Trie**
A **Trie** is a tree-like data structure where each node represents a **bit** (0 or 1).
- Each integer is represented as a **32-bit binary number** (since integers fit in 32 bits).
- The Trie allows fast bitwise lookups to determine the best XOR match.
- Every node contains two child pointers (`0` and `1`).
**Insertion Process**:
- We insert all numbers from `0` to `2^maximumBit - 1` into the Trie.
- This ensures that for any given number, we can find the best XOR match.
---
### Step 3: **Computing Cumulative XOR**
- We maintain a **running XOR** of the entire array, which helps in computing the required XOR dynamically.
- We traverse the array in reverse order, updating the XOR by removing elements one by one.
---
### Step 4: **Finding Maximum XOR Using the Trie**
For each query:
1. Compute the cumulative XOR of the array up to that point.
2. Use the Trie to find the **best possible number `k`** such that `XOR ⊕ k` is maximized.
3. The best `k` is determined by trying to match opposite bits in the Trie.
4. Store the result and update the cumulative XOR by removing the last element.
---
### Step 5: **Updating the XOR for Each Query**
- Since we need answers in reverse order, we start from the entire array and remove elements one by one.
- After each query, we remove the last inserted element from the cumulative XOR.
---
# Complexity Analysis
### **Time Complexity**
1. **Building the Trie**:
- We insert `2^maximumBit` numbers, and each number has `maximumBit` bits.
- This takes **O(2^maximumBit * maximumBit)**.
2. **Processing Each Query**:
- Each query takes **O(maximumBit)** to traverse the Trie.
- We process `n` queries, leading to **O(n * maximumBit)**.
3. **Overall Complexity**:
- **O((n + 2^maximumBit) * maximumBit)**.
### **Space Complexity**
- The Trie stores `2^maximumBit` numbers, each requiring `maximumBit` nodes.
- Total space complexity: **O(2^maximumBit * maximumBit)**.
# Code
```cpp []
class node {
public:
node* links[2];
node() {
for (int i = 0; i < 2; i++) {
this->links[i] = NULL;
}
}
node* get(int x) {
return this->links[x];
}
bool contains(int x) {
return links[x] != nullptr;
}
void put(int x, node* newnode) {
this->links[x] = newnode;
}
};
class Trie {
public:
node* root = nullptr;
Trie() {
root = new node();
}
void insert(int x) {
node* temp = root;
for (int i = 31; i >= 0; i--) {
int bit = (x >> i) & 1;
if (!temp->contains(bit)) {
temp->put(bit, new node());
}
temp = temp->get(bit);
}
}
int bestk(int num) {
node* temp = root;
int k = 0;
for (int i = 31; i >= 0; i--) {
int bit = (num >> i) & 1;
int reqbit = 1 - bit;
if (temp->contains(reqbit)) {
temp = temp->get(reqbit);
k |= (reqbit << i);
} else {
k |= (bit << i);
temp = temp->get(bit);
}
}
return k;
}
};
class Solution {
public:
vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {
int n = nums.size();
int m = pow(2,maximumBit) - 1;
Trie* trie = new Trie();
vector<int>ans;
for(int i = 0; i <= m; i++){
trie->insert(i);
}
int xorOfarr = 0;
for(int i = 0 ; i < n; i++){
xorOfarr ^= nums[i];
}
for(int i = 0 ; i < n; i++){
ans.push_back(trie->bestk(xorOfarr));
xorOfarr ^= nums[n - 1 - i];
}
return ans;
}
};
``` | 1 | 0 | ['C++'] | 0 |
maximum-xor-for-each-query | Bit Manipulation | O(N) Solution | bit-manipulation-on-solution-by-sahil_lo-55ol | Solution:
Everytime taking the xor of whole array will take O(N) time, so we can take the xor of whole array one time and in queries we can remove xor of last e | sahil_lohar_nitr | NORMAL | 2025-03-17T13:47:26.168817+00:00 | 2025-03-17T13:47:26.168817+00:00 | 12 | false | # Solution:
1) Everytime taking the xor of whole array will take O(N) time, so we can take the xor of whole array one time and in queries we can remove xor of last ele, how? if we take the xor of the finalXor with the last ele, acc to xor property(n^n = 0) the ele will be removed fron the finalXor.
2) To maximize the finalXor : how can we maximixe the answer => if all the bits of answer are set => answer is maximized, so to maximize the xor, we have to take a number, so that if we do xor with finalXor, we get ...11111, to do this if we take xor of that number with 1111111111 (mask of all ones) we will get the fliped number which will the value of k.
3) For eg. if we want to maximize finalXor = 101 by taking xor with some value x, the maximized answer will be 111, so to get this answer, we have to take xor of 101 with 010, hence we have to find the flipped version of 101 and that can be find by taking xor of 101 with 111 i.e (1LL<<3)-1
4) For mask of all ones ..11111 ---> (1LL<<3)-1 = 111
# Complexity
- Time complexity : O(N)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
typedef long long ll;
vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {
ll n = nums.size();
vector<int> res(n);
ll xorValue = 0;
for (int i{}; i < n; i++) {
xorValue ^= nums[i];
}
for (int i{}; i < n; i++) {
ll mask = (1ll << maximumBit) - 1;
res[i] = (xorValue ^ mask);
xorValue ^= nums[nums.size() - 1];
nums.pop_back();
}
return res;
}
};
``` | 1 | 0 | ['Array', 'Bit Manipulation', 'C++'] | 0 |
maximum-xor-for-each-query | Easy Solution | easy-solution-by-harshulgarg-hekc | IntuitionThe problem requires computing the maximum XOR value for each prefix of the array when XORed with a number that has all maximumBit bits set to 1.The ke | harshulgarg | NORMAL | 2025-02-14T12:33:22.945162+00:00 | 2025-02-14T12:33:22.945162+00:00 | 9 | false | # Intuition
The problem requires computing the maximum XOR value for each prefix of the array when XORed with a number that has all maximumBit bits set to 1.
The key observation is that for any number x, the value x ^ m (where m has all maximumBit bits set) gives the maximum possible XOR.
We maintain a running XOR of the elements to efficiently compute results.
# Approach
Compute m:
m = (2**maximumBit) - 1, which is equivalent to 111...1 (all maximumBit bits set).
Maintain a running XOR (c):
Iterate through nums, updating c = c ^ num at each step.
Compute c ^ m to get the maximum XOR value at each step and store it in the list a.
Reverse the list:
Since results are computed in increasing order but need to be returned in reverse order, we return a[::-1].
# Complexity
- Time complexity:
O(n)
- Space complexity:
$O(n)$$ -->
# Code
```python3 []
class Solution:
def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:
m=(2**maximumBit)-1
a=[]
c=0
for i in nums:
c=c^i
a.append(c^m)
return a[::-1]
``` | 1 | 0 | ['Array', 'Python3'] | 0 |
partition-array-such-that-maximum-difference-is-k | [Java/C++/Python] Sort + Greedy | javacpython-sort-greedy-by-lee215-11b6 | Explanation\nmn means the minimum number in the current sequence.\nmx means the maximum number in the current sequence.\n\nIterate each element A[i] in the inpu | lee215 | NORMAL | 2022-06-05T04:12:55.264329+00:00 | 2022-06-05T04:12:55.264372+00:00 | 8,442 | false | # **Explanation**\n`mn` means the minimum number in the current sequence.\n`mx` means the maximum number in the current sequence.\n\nIterate each element `A[i]` in the input array,\nand we try to add it into the current subsequence.\n\nWe need to check if the differnce is still good.\nSo we firstly update the value of `mn` and `mx`\n`mn = min(mn, a)`\n`mx = max(mx, a)`.\n\n\nIf `mx - mn > k`,\nthis means the difference between the maximum and minimum values,\nis bigger than `k` in current subsequence,\n\n`A[i]` cannot be added to the subsequence,\nso we start a new subsequence with `A[i]` as the first element,\nthus increment `res` and update `mn = mx = a`.\n\nWe continue doing this process and finally return result `res`.\n\nThen I notice it\'s subsequences instead of subarray,\nI added a sort at the beginning.....\n<br>\n\n# **Complexity**\nTime `O(sort)`\nSpace `O(sort)`\n<br>\n\n**Java**\n```java\n public int partitionArray(int[] A, int k) {\n Arrays.sort(A);\n int res = 1, mn = A[0], mx = A[0];\n for (int a: A) {\n mn = Math.min(mn, a);\n mx = Math.max(mx, a);\n if (mx - mn > k) {\n res++;\n mn = mx = a;\n }\n }\n return res;\n }\n```\n\n**C++**\n```cpp\n int partitionArray(vector<int>& A, int k) {\n sort(A.begin(), A.end());\n int res = 1, mn = A[0], mx = A[0];\n for (int& a: A) {\n mn = min(mn, a);\n mx = max(mx, a);\n if (mx - mn > k) {\n res++;\n mn = mx = a;\n }\n }\n return res;\n }\n```\n\n**Python**\n```py\n def partitionArray(self, A, k):\n A.sort()\n res = 1\n mn = mx = A[0]\n for a in A:\n mn = min(mn, a)\n mx = max(mx, a)\n if mx - mn > k:\n res += 1\n mn = mx = a\n return res\n```\n\n# Solution II\n**Java**\n```java\n public int partitionArray(int[] A, int k) {\n Arrays.sort(A);\n int res = 1, n = A.length, j = 0;\n for (int i = 1; i < n; ++i) {\n if (A[i] - A[j] > k) {\n res++;\n j = i;\n }\n }\n return res;\n }\n```\n\n**C++**\n```cpp\n int partitionArray(vector<int>& A, int k) {\n sort(A.begin(), A.end());\n int res = 1, n = A.size(), j = 0;\n for (int i = 1; i < n; ++i) {\n if (A[i] - A[j] > k) {\n res++;\n j = i;\n }\n }\n return res;\n }\n```\n**Python**\n```py\n def partitionArray(self, A, k):\n A.sort()\n res, j = 1, 0\n for i in range(len(A)):\n if A[i] - A[j] > k:\n res += 1\n j = i\n return res\n```\n | 70 | 6 | ['C', 'Python', 'Java'] | 16 |
partition-array-such-that-maximum-difference-is-k | Sort and select | sort-and-select-by-surajthapliyal-w9l7 | Sort the array \n And select maximum gap of max element - min element\n If difference >= k then only increase answer and make start of another subsequence as it | surajthapliyal | NORMAL | 2022-06-05T04:00:42.207322+00:00 | 2022-06-05T04:14:12.503978+00:00 | 3,382 | false | * Sort the array \n* And select maximum gap of max element - min element\n* If difference >= k then only increase answer and make start of another subsequence as ith element.\n\nTime - O(sort)\n```\nclass Solution {\n\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int c = 1, prev = 0;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] - nums[prev] <= k) continue;\n c++; prev = i;\n }\n return c;\n }\n}\n```\n | 33 | 0 | ['Sorting', 'Java'] | 11 |
partition-array-such-that-maximum-difference-is-k | Python Easy Solution using Sorting | python-easy-solution-using-sorting-by-mi-1ol7 | Explanation:\n\nInitially I did think it as a DP problem because of the word "subsequence" and "minimum". But after analysing the array and output I realized we | mikueen | NORMAL | 2022-06-05T04:01:38.083617+00:00 | 2022-06-07T04:19:24.935647+00:00 | 2,032 | false | ### Explanation:\n\nInitially I did think it as a DP problem because of the word "**subsequence**" and "**minimum**". But after analysing the array and output I realized we are more concerned about "**at most difference should be K**", and the at most difference is of min element and max element of subsequence, so what\'s better than sorting? Sorting gives min and max element.\n\nYes, we are changing the order of elements but it wouldnt matter because we dont need to return the exact subsequences, we need to return the count of subsequences.\n\n**Example:**\n\n*before sort:*\nnums -> [3, 6, 1, 2, 5]\nsubsequences -> [3, 1, 2], [6, 5]\noutput -> 2\n\n*after sort:*\nnums -> [1, 2, 3, 5, 6]\nsubsequences -> [1, 2, 3], [5, 6]\noutput -> 2\n\nSo the order of elements would change but the elements inside each subsequence would remain same.\n\n\n```\nclass Solution:\n def partitionArray(self, nums: List[int], k: int) -> int:\n nums.sort()\n ans = 1\n\t\t# To keep track of starting element of each subsequence\n start = nums[0]\n \n for i in range(1, len(nums)):\n diff = nums[i] - start\n if diff > k:\n\t\t\t\t# If difference of starting and current element of subsequence is greater\n\t\t\t\t# than K, then only start new subsequence\n ans += 1\n start = nums[i]\n \n return ans | 26 | 1 | ['Sorting', 'Python', 'Python3'] | 6 |
partition-array-such-that-maximum-difference-is-k | Easy | easy-by-kamisamaaaa-kf5v | Here we only have to tell the number of subsequences and we can use an element only once that\'s why we can sort the array.\n\n\nclass Solution {\npublic:\n | kamisamaaaa | NORMAL | 2022-06-05T04:06:20.147471+00:00 | 2022-06-05T05:36:54.359836+00:00 | 1,649 | false | **Here we only have to tell the number of subsequences and we can use an element only once that\'s why we can sort the array.**\n\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n \n int n(size(nums)), res(0);\n sort(begin(nums), end(nums));\n \n for (int start=0, next=0; start<n;) {\n while (next<n and nums[next]-nums[start] <= k) next++; \n start = next;\n res++;\n }\n return res;\n }\n};\n``` | 15 | 1 | ['C'] | 2 |
partition-array-such-that-maximum-difference-is-k | Two Pointers | two-pointers-by-votrubac-fizr | Sort, then use two pointers to track the current valid subsequence. Start a new subsequence if nums[i] cannot be added to the current one.\n\nAs the second poin | votrubac | NORMAL | 2022-06-05T05:17:31.997173+00:00 | 2022-06-05T07:25:52.247464+00:00 | 1,866 | false | Sort, then use two pointers to track the current valid subsequence. Start a new subsequence if `nums[i]` cannot be added to the current one.\n\nAs the second pointer, we use the last element of the `subs` array. This could be handy if we need to identify subarrays in the end, for some reason.\n\n**C++**\n```cpp\nint partitionArray(vector<int>& nums, int k) {\n sort(begin(nums), end(nums));\n vector<int> subs{nums[0]};\n for (int i = 1; i < nums.size(); ++i)\n if (nums[i] - subs.back() > k)\n subs.push_back(nums[i]);\n return subs.size();\n}\n``` | 14 | 0 | [] | 5 |
partition-array-such-that-maximum-difference-is-k | [Java/Python 3] Sort and count, w/ brief explanation and analysis. | javapython-3-sort-and-count-w-brief-expl-mwyi | Greedy algorithm.\n\n----\n\nmethod 1: two pointers\n1. Sort nums, starting from 1st two elements, nums[0] and nums[1], as the values that two pointers prev and | rock | NORMAL | 2022-06-05T04:10:41.401461+00:00 | 2022-06-08T13:39:50.541228+00:00 | 743 | false | Greedy algorithm.\n\n----\n\n**method 1: two pointers**\n1. Sort `nums`, starting from 1st two elements, `nums[0]` and `nums[1]`, as the values that two pointers `prev` and `cur` initially point to; Initialize a counter `partitions` as `1` since we at lease have `1` partition;\n2. if `nums[cur] - nums[prev] > k`, increase the counter by `1` and update `prev` and `cur` accordingly;\n3. Repeat 2 till the end of `nums`.\n```java\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int partitions = 1;\n for (int cur = 1, prev = 0; cur < nums.length; ++cur) {\n if (nums[cur] - nums[prev] > k) {\n ++partitions; \n prev = cur;\n }\n }\n return partitions;\n }\n```\n```python\n def partitionArray(self, nums: List[int], k: int) -> int:\n nums.sort()\n prev, partitions, n = 0, 1, len(nums)\n for cur in range(1, n):\n if nums[cur] - nums[prev] > k:\n partitions += 1\n prev = cur\n return partitions\n```\n\n----\n\nWe can use binary search after sorting, which is of course only a minor optimiztaton.\n\n**Method 2: binary search**\n\n1. Sort `nums`, starting from 1st element, `nums[0]`, binary search the index of the ceil of `nums[0] + k`, `nums[0] + 2 * k`, ...`nums[0] + i * k`,.., respectively, till reach the last element of `nums`;\n2. Increase the partitions by `1` whenever find each during the binary search in 1.\n```java\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int key = nums[0] + k, partitions = 1;\n while (binarySearch(nums, key) < nums.length) {\n ++partitions;\n key = nums[binarySearch(nums, key)] + k;\n }\n return partitions;\n }\n private int binarySearch(int[] nums, int key) {\n int lo = 0, hi = nums.length;\n while (lo < hi) {\n int mid = lo + (hi - lo) / 2;\n if (nums[mid] <= key) {\n lo = mid + 1;\n }else {\n hi = mid;\n }\n }\n return lo;\n }\n```\n```python\n def partitionArray(self, nums: List[int], k: int) -> int:\n nums.sort()\n partitions = 1\n cur = nums[0]\n while (idx := bisect.bisect(nums, cur + k)) < len(nums):\n partitions += 1\n cur = nums[idx]\n return partitions \n```\n\n**Analysis:**\n\nTime: `O(nlogn)`, space: `O(n)` - including sorting space, where `n = nums.length`. | 12 | 0 | [] | 1 |
partition-array-such-that-maximum-difference-is-k | Max Heap/Priority Queue || C++ Solution | max-heappriority-queue-c-solution-by-shi-lm6n | \nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n priority_queue<int> pq;\n for(int i=0;i<nums.size();i++)\n | Shishir_Sharma | NORMAL | 2022-06-05T04:03:25.587158+00:00 | 2022-06-05T04:03:25.587189+00:00 | 928 | false | ```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n priority_queue<int> pq;\n for(int i=0;i<nums.size();i++)\n {\n pq.push(nums[i]);\n }\n int last=-1;\n int count=0;\n while(pq.size()>0)\n {\n int t=pq.top();\n pq.pop();\n if(last!=-1)\n {\n if(last-t<=k)\n {\n continue;\n }\n else\n {\n last=t;\n count++;\n }\n }\n else\n { count++;\n last=t;\n }\n }\n return count;\n }\n};\n```\n**Like it? Please Upvote ;-)** | 9 | 2 | ['C', 'C++'] | 2 |
partition-array-such-that-maximum-difference-is-k | C++ | PYTHON | JAVA | Sort | Short and Clean | c-python-java-sort-short-and-clean-by-am-5c1g | CPP\n\n\nclass Solution {\npublic:\n int partitionArray(vector<int>& v, int k,int ans=0,int idx=0) {\n sort(v.begin(),v.end());\n for(int i=0;i | amirkpatna | NORMAL | 2022-06-05T04:01:59.624351+00:00 | 2022-06-05T04:39:28.567368+00:00 | 696 | false | **CPP**\n\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& v, int k,int ans=0,int idx=0) {\n sort(v.begin(),v.end());\n for(int i=0;i<v.size();i++){\n if(v[i]-v[idx]>k)ans++,idx=i;\n }\n return ans+1;\n }\n};\n```\n\n**PYTHON**\n\n```\nclass Solution:\n def partitionArray(self, v: List[int], k: int,idx=0 ,ans=0) -> int:\n v.sort()\n for i in range(len(v)):\n if v[i] - v[idx]>k:\n ans+=1\n idx=i\n return ans+1\n \n```\n\n**JAVA**\n\n```\nclass Solution {\n public int partitionArray(int[] v, int k) {\n Arrays.sort(v);\n int ans=0,idx=0;\n for(int i=0;i<v.length;i++){\n if(v[i]-v[idx]>k){\n ans++;idx=i;\n }\n }\n return ans+1;\n }\n}\n``` | 9 | 1 | ['Greedy', 'C', 'Sorting', 'Python', 'Java'] | 3 |
partition-array-such-that-maximum-difference-is-k | [Java] O(n) Turns out Bucket is faster in this solution, 7ms beats 100% | java-on-turns-out-bucket-is-faster-in-th-l4gk | After you put nums into buckets, scan it, if it appeared, then jump k steps.\nTo shorten time, it could check only from smallest to biggest in buckets.\n\nclass | zero2424 | NORMAL | 2022-06-05T04:21:22.239724+00:00 | 2022-06-05T04:34:28.878018+00:00 | 573 | false | After you put nums into buckets, scan it, if it appeared, then jump k steps.\nTo shorten time, it could check only from smallest to biggest in buckets.\n```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n int[] buckets=new int[(int)(Math.pow(10,5)+1)];\n int max=0;\n for(int num:nums){\n buckets[num]++;\n max=Math.max(max,num);\n }\n int result=0;\n for(int i=0;i<=max;i++){\n if(buckets[i]>0){\n result++;\n i+=k;\n }\n }\n return result;\n }\n}\n``` | 8 | 0 | ['Java'] | 2 |
partition-array-such-that-maximum-difference-is-k | FULLY EXPLAINED!! | fully-explained-by-shourya112001-p5nx | \'\'\'\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n \n // sorted array - so that we can simply traverse for min and max | Shourya112001 | NORMAL | 2022-06-05T04:08:59.503994+00:00 | 2022-06-05T05:28:35.110127+00:00 | 687 | false | \'\'\'\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n \n // sorted array - so that we can simply traverse for min and max elements\n \n Arrays.sort(nums);\n \n int min = nums[0]; //obvious\n int max;\n \n int result = 1; //intially our whole array is a subsequence for us\n \n for(int i=0;i<nums.length;i++)\n {\n // we have to traverse ahead till the min and the max difference is smaller than that of k\n // so that we can get the max of our first subsequence and thereon further subsequences\n \n max = nums[i];\n \n if((max - min) > k) // if it exceeds - we will have to make a new subsequence\n {\n result++;\n \n // and when getting to another subsequence, we will also have to update our min value\n \n min = nums[i];\n }\n }\n \n return result;\n }\n}\n\'\'\' | 7 | 1 | ['Java'] | 6 |
partition-array-such-that-maximum-difference-is-k | [Python 3] Sort + Greedy - Simple Solution | python-3-sort-greedy-simple-solution-by-mig3d | 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 | dolong2110 | NORMAL | 2023-07-24T14:48:51.418660+00:00 | 2023-07-24T14:48:51.418682+00:00 | 194 | 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(NlogN)$$\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 partitionArray(self, nums: List[int], k: int) -> int:\n nums.sort()\n j = 0\n res = 1\n for i, num in enumerate(nums):\n if num - nums[j] > k:\n res += 1\n j = i\n return res\n``` | 6 | 0 | ['Greedy', 'Sorting', 'Python3'] | 0 |
partition-array-such-that-maximum-difference-is-k | Very easy Java solution | very-easy-java-solution-by-gau5tam-kxb1 | Please UPVOTE if you like my solution!\n\n\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n if(nums.length == 1){\n ret | gau5tam | NORMAL | 2023-03-27T14:22:43.495880+00:00 | 2023-03-27T14:22:43.495916+00:00 | 375 | false | Please **UPVOTE** if you like my solution!\n\n```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n if(nums.length == 1){\n return 1;\n }\n Arrays.sort(nums);\n int count = 0;\n for(int i = 1,j = 0;i<nums.length;i++){\n if(nums[i] - nums[j] <= k){\n continue;\n }\n else{\n count++;\n j = i;\n }\n }\n return count+1;\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
partition-array-such-that-maximum-difference-is-k | Cpp Solution Better than 100% O(nlogn) Time Complexity | cpp-solution-better-than-100-onlogn-time-dylr | Approach\n-> The idea is to sort the array in decending order and then apply two pointers the first pointer will point to the first element of any partition and | Indominous1 | NORMAL | 2022-11-26T19:09:33.695951+00:00 | 2022-11-26T19:09:33.695987+00:00 | 385 | false | # Approach\n-> The idea is to sort the array in decending order and then apply two pointers the first pointer will point to the first element of any partition and second pointer will traverse and find the last element of the partition \n\n-> The job of second pointer is find to the element whose difference with the element (first pointer is pointing) is greater than the value k, and when we find that element simply increase the value of partition variable (this variable is counting the number of partions we require) \n\n-> The answer of the query is value of partition variable + 1 (because we need to return number of subsequences or partition)\n\n```\nGiven nums = [3,6,1,2,5], k = 2\n part = 0\n-> nums = 6 5 3 2 1 // After Sorting in Descending order\n | |\n i j // Pointers\n n[i]-n[j] = 1 < 2 //ignore and increment value of j\n\n\n-> nums = 6 5 3 2 1\n | |\n i j\n n[i]-n[j] = 3 > 2 // increment partition variable\'s value by 1 and do i=j\n\n\n-> Now, nums = 6 5 | 3 2 1\n | |\n i j\n n[i]-n[j] = 1 < 2 // ignore and increment value of j\n\n\n nums = 6 5 | 3 2 1\n | |\n i j \n n[i]-n[j] = 2 == 2 //ignore and increment value of j\n\n\n j == n.size() therefore terminate the loop \n\n```\n\n```\nPLease Like if find the code interesting\uD83D\uDE01\uD83D\uDE01\uD83D\uDE0A\uD83D\uDE0A\n```\n\n# Complexity\n- Time complexity: O(nlogn + n) ,better than 100% Cpp online Submissions\n\n- Space complexity: O(1), better than 52% Cpp online Submissions\n\n# Code\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& n, int k) {\n int part=0;\n sort(n.begin(),n.end(),greater<int>());\n int i=0,j=1;\n while(i<n.size() && j<n.size())\n {\n if(n[i]-n[j]>k)\n {\n part++;\n i=j;\n }\n j++;\n }\n return part+1; }\n};\n``` | 6 | 0 | ['Two Pointers', 'Greedy', 'C', 'Sorting', 'C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | C++ | 108ms[O(n)] & 83 MB[O(n)] (100%/86%) | counting sort | explanation | c-108mson-83-mbon-10086-counting-sort-ex-q641 | \nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int rt=0,ma=0,mi=100000;\n bool ct[100005]={0};\n for(int | SunGod1223 | NORMAL | 2022-06-09T02:08:02.559350+00:00 | 2022-06-11T04:20:35.296668+00:00 | 225 | false | ```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int rt=0,ma=0,mi=100000;\n bool ct[100005]={0};\n for(int i=0;i<nums.size();++i){\n ma=max(ma,nums[i]);\n mi=min(mi,nums[i]);\n ct[nums[i]]=1;\n }\n\t\tif(k>=ma-mi)\n return 1;\n for(int i=mi;i<=ma;++i){\n if(ct[i]){\n ++rt;\n i+=k;\n }\n }\n return rt;\n }\n};\n```\n1.we don\'t need to count the times of each number because it is equivalence between [2] and [2,2,2] **->** use boolean array to reduce memory use.\n2.we don\'t need to traverse each number after counting sort **->** when a single number x apper in nums, x ~ x+k is the best way to partition (greedy).\n3.we don\'t need to traverse from 0 to 10000 for every test case **->** recording the min/max value of nums and iterating over them.\n4.if (k >= max-min) and (the size of nums > 0) **->** the answer is 1. | 6 | 0 | ['Greedy', 'Counting Sort'] | 0 |
partition-array-such-that-maximum-difference-is-k | Greedy Using TreeSet | greedy-using-treeset-by-pavankumarchaita-z6cn | ```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n TreeSet ts = new TreeSet<>();\n for(int num: nums){\n ts.add | pavankumarchaitanya | NORMAL | 2022-06-05T04:05:57.088876+00:00 | 2022-06-05T04:05:57.088909+00:00 | 176 | false | ```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n TreeSet<Integer> ts = new TreeSet<>();\n for(int num: nums){\n ts.add(num);\n }\n\n Integer start = ts.first();\n int count = 0;\n while(start!=null && ts.ceiling(start)!=null){\n int end = start+k;\n count++;\n if(ts.ceiling(end+1)==null)\n return count;\n if(ts.contains(end+1))\n start = end+1;\n else\n start = ts.ceiling(end+1); \n }\n return count;\n }\n}\n | 6 | 2 | [] | 2 |
partition-array-such-that-maximum-difference-is-k | [C++] | Smooth Solution clearly EXPLAINED!! | c-smooth-solution-clearly-explained-by-s-nbv5 | dry run with steps:\nnums = [3 6 1 2 5], k= 2\nstep-1: sort in decreasing order\n6 5 3 2 1\nStep-2: count sub-sequences (if the difference between elements (num | shm_47 | NORMAL | 2022-06-06T19:34:45.750217+00:00 | 2022-06-06T19:36:21.965542+00:00 | 326 | false | **dry run with steps:**\nnums = [3 6 1 2 5], k= 2\n**step-1:** sort in decreasing order\n6 5 3 2 1\n**Step-2:** count sub-sequences (if the difference between elements (nums[j]- nums[i] > k) book a new subsequence).\n6-5 = 1 | j = 0, ans = 1\n6-3 = 3> k | j = 2, ans = 2\n3-2 = 1 | j = 2, ans = 2\n3-1 = 2 | j = 2, ans = 2\n\n\n**Code:**\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int j = 0;\n int ans = 1; //complete array is 1 subsequence in itself\n \n //sort in decreasing fashion\n sort(nums.begin(), nums.end(), greater<int>());\n \n //if the difference between elements (nums[j]- nums[i] > k) book a new subsequence\n for(int i=1; i<nums.size(); i++){\n if(nums[j]- nums[i] > k){\n ans++;\n j = i;\n }\n }\n \n return ans;\n }\n};\n```\n\n**Please do upvote if you like the solution:)** | 5 | 0 | ['C', 'Sorting', 'C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | C++ || sorting || Easy-to-understand | c-sorting-easy-to-understand-by-pitbull_-q3ps | \nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int n=nums.size();\n sort(nums.begin(),nums.end(),greater<int>() | Pitbull_45 | NORMAL | 2022-06-05T04:02:49.174581+00:00 | 2022-06-05T06:32:05.103714+00:00 | 387 | false | ```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int n=nums.size();\n sort(nums.begin(),nums.end(),greater<int>());\n int s=nums[0];\n int cnt=0;\n for(int i=1;i<n;i++){\n if(s-nums[i]>k){\n s=nums[i];\n cnt++;\n }\n }\n cnt++;\n return cnt;\n }\n};\n```\n**Don\'t forget to upvote this post if it has helped you!!!** | 5 | 0 | [] | 1 |
partition-array-such-that-maximum-difference-is-k | Simple Cpp solution | simple-cpp-solution-by-shivamg4149-h3lx | \nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int n=nums.size();\n if(n==1)\n return 1;\n so | shivamg4149 | NORMAL | 2022-06-05T04:01:42.234427+00:00 | 2022-06-05T04:01:42.234469+00:00 | 325 | false | ```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int n=nums.size();\n if(n==1)\n return 1;\n sort(nums.begin(),nums.end());\n int i=0;\n int j=i+1;\n int ans=0;\n while(j<n && i<n){\n if(k>=nums[j]-nums[i]){\n j++;\n }\n else{\n ans++;\n i=j;\n j=i+1;\n }\n }\n ans++;\n return ans;\n }\n};\n``` | 5 | 0 | ['Sorting', 'C++'] | 2 |
partition-array-such-that-maximum-difference-is-k | C++ Easy Code | c-easy-code-by-mayanksamadhiya12345-at6w | Please Upvote If It Helps\n\n\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end());\n | mayanksamadhiya12345 | NORMAL | 2022-06-06T16:58:12.841665+00:00 | 2022-06-06T16:58:12.841702+00:00 | 119 | false | **Please Upvote If It Helps**\n\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end());\n int cnt = 0;\n int flag = 1;\n int n = nums.size();\n int mn = INT_MAX;\n \n for(int i=0;i<n;i++)\n {\n // if our flag is 1 it means we are ready with new subsequence\n if(flag==1)\n {\n flag = 0;\n mn = nums[i];\n cnt++;\n }\n \n // if our consecutive diff is greater than k then we need to start new subsequence\n if(nums[i]-mn > k)\n {\n flag = 1; // made flag 1 to start the new subsequence\n mn = INT_MAX; // make again mn as max\n i--; // move curr pointer , 1 step behind\n }\n }\n return cnt;\n \n }\n};\n```\n | 4 | 1 | [] | 0 |
partition-array-such-that-maximum-difference-is-k | [Python3] Heap | python3-heap-by-frolovdmn-qiuw | The idea is to iteratively build subsequences from nums using heap while maintaining the property that each element appears in exactly one subsequence.
We initi | frolovdmn | NORMAL | 2022-06-05T09:56:19.946025+00:00 | 2025-01-19T14:21:58.295077+00:00 | 216 | false | The idea is to iteratively build subsequences from nums using heap while maintaining the property that each element appears in exactly one subsequence.
We initialize a variable **start** to store the first element of the current subsequence and **count** to store the number of subsequences required and set it to 1. While there are still elements left in the **heap**, we pop the smallest element from the heap using the heappop() and assign it to **num**. If the difference between **num** and **start** is greater than **k**, it means that the current subsequence has exceeded the allowed difference of k. Therefore, we update start to be equal to num and increment the count variable to indicate a new subsequence. After popping all elements from the heap, we return **count** variable which stores the minimum number of subsequences.
```python []
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
heapify(nums)
count = 1
start = heappop(nums)
while nums:
num = heappop(nums)
if num - start > k:
start = num
count += 1
return count
``` | 4 | 0 | ['Heap (Priority Queue)', 'Python', 'Python3'] | 0 |
partition-array-such-that-maximum-difference-is-k | ✅C++ | Sort & Two Pointer | Most simple approach | c-sort-two-pointer-most-simple-approach-3p28x | \nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int i,j=0, cnt=0;\n for( | rupam66 | NORMAL | 2022-06-05T04:52:58.278335+00:00 | 2022-06-05T04:52:58.278364+00:00 | 304 | false | ```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int i,j=0, cnt=0;\n for(int i=0;i<nums.size();i++){\n if(nums[i]-nums[j]>k){\n cnt++;\n j=i;\n }\n }\n return cnt+1;\n }\n};\n``` | 4 | 0 | ['C', 'Sorting'] | 1 |
partition-array-such-that-maximum-difference-is-k | ✅C++ | Use sorting and flag | Explanation through comments | c-use-sorting-and-flag-explanation-throu-qa9g | Please upvote if you find this solution helpful:)\nTC: O(NlogN), SC: O(1)\n\nCode:\n\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k | Yash2arma | NORMAL | 2022-06-05T04:26:25.240412+00:00 | 2022-06-05T07:47:15.338789+00:00 | 174 | false | **Please upvote if you find this solution helpful:)\nTC: O(NlogN), SC: O(1)**\n\n**Code:**\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) \n {\n //sort nums to get all values in ascending order \n sort(nums.begin(), nums.end());\n int n=nums.size(), count=0, flag=0, mini=INT_MAX;\n \n \n //iterate through the nums\n for(int j=0; j<n; j++)\n {\n //when flag is 0 \n if(!flag)\n {\n flag=1; //mark flag=1 which shows new subsequence started\n mini = nums[j]; //since nums is in ascending order, mini will be at first index of new subsequence\n count++;\n }\n\n //when difference is greater than k we need to start new subsequence\n if(abs(nums[j]-mini) > k)\n {\n //re-assign flag=0, mini, and decrement j, to consider it in new subsequence\n flag=0; \n mini = INT_MAX; \n j--;\n }\n }\n \n return count;\n }\n};\n``` | 4 | 0 | ['Array', 'C', 'Sorting', 'C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | 📌 4 Liner || Sort + Two Pointer | 4-liner-sort-two-pointer-by-avi_g10-awvc | Point to be Noted : There should be minimum one Partition Always.\n\t\n\t\n\tclass Solution {\n\tpublic:\n\t\tint partitionArray(vector& nums, int k) {\n\t\t\ti | Avi_G10 | NORMAL | 2022-06-05T04:10:04.716713+00:00 | 2022-06-05T04:51:16.996494+00:00 | 64 | false | **Point to be Noted :** *There should be minimum one Partition Always.*\n\t\n\t\n\tclass Solution {\n\tpublic:\n\t\tint partitionArray(vector<int>& nums, int k) {\n\t\t\tint start = 0,end = 0,ans = 1;\n\t\t\tsort(nums.begin(),nums.end());\n\t\t\twhile(end != nums.size()){\n\t\t\t\tif(nums[end] - nums[start] <= k) end++;\n\t\t\t\telse ans++, start = end;\n\t\t\t}\n\t\t\treturn ans;\n\t\t}\n\t};\n\t\n**Time Complexity :** *O(nlogn)*\n**Space Complexity :** *O(1)* | 4 | 0 | ['Sorting'] | 0 |
partition-array-such-that-maximum-difference-is-k | ✅ Greedy Approach ✅ 4 line solution with sorting ✅ | greedy-approach-4-line-solution-with-sor-ckyz | \n# Code\njava []\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n if (nums.length <= 1) {\n return nums.length;\n | menezes1997 | NORMAL | 2024-08-21T17:48:45.640755+00:00 | 2024-08-21T17:48:45.640784+00:00 | 106 | false | \n# Code\n```java []\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n if (nums.length <= 1) {\n return nums.length;\n }\n Arrays.sort(nums);\n\n int min_value = nums[0];\n int countOfSets = 1;\n\n for (int i = 1; i < nums.length; i++) {\n if (nums[i] - min_value <= k) {\n continue;\n } else {\n countOfSets++;\n min_value = nums[i];\n }\n }\n return countOfSets;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
partition-array-such-that-maximum-difference-is-k | SIMPLE TWO-POINTER + GREEDY C++ COMMENTED | simple-two-pointer-greedy-c-commented-by-mtzg | 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 | Jeffrin2005 | NORMAL | 2024-08-16T12:45:51.557182+00:00 | 2024-08-16T12:45:51.557207+00:00 | 94 | 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\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n \n int count = 0; // This will hold the number of subsequences\n int i = 0; // Iterator for the nums array\n while(i < nums.size()){\n count++; // Start a new subsequence\n int start = nums[i]; // The minimum element of the current subsequence\n // Add as many elements as possible to the current subsequence\n while(i < nums.size() && nums[i] - start <= k){\n i++;\n }\n }\n \n return count;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | 3 Solutions for Partition Array Such That Maximum Difference Is K in C++ | 3-solutions-for-partition-array-such-tha-8ukh | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# 1. Approach\n Describe your approach to solving the problem. \nBRUTE FORCE -> SORTI | The_Kunal_Singh | NORMAL | 2023-05-11T02:52:52.685127+00:00 | 2023-05-11T02:52:52.685162+00:00 | 128 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# 1. Approach\n<!-- Describe your approach to solving the problem. -->\n*BRUTE FORCE -> SORTING*\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int i, j, min, count=1;\n sort(nums.begin(), nums.end());\n min = nums[0];\n for(i=1 ; i<nums.size() ; i++)\n {\n if(nums[i]-min>k)\n {\n count++;\n min = nums[i];\n }\n }\n return count;\n }\n};\n```\n# 2. Approach\n<!-- Describe your approach to solving the problem. -->\n*USING HASHMAP*\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(n)\n# Code\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int i, min=-1, count=1;\n map<int, int> mp;\n for(i=0 ; i<nums.size() ; i++)\n {\n mp[nums[i]]++;\n }\n for(auto it:mp)\n {\n if(min==-1)\n {\n min = it.first;\n }\n else if(it.first-min>k)\n {\n min = it.first;\n count++;\n }\n }\n return count;\n }\n};\n```\n# 3. Approach\n<!-- Describe your approach to solving the problem. -->\n*USING SET*\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(n)\n# Code\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int i, min=-1, count=1;\n set<int> s(nums.begin(), nums.end());\n for(auto it:s)\n {\n if(min==-1)\n {\n min = it;\n }\n else if(it-min>k)\n {\n min = it;\n count++;\n }\n }\n return count;\n }\n};\n```\n\n | 3 | 0 | ['C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | Simple Python Solution | simple-python-solution-by-jigglyypuff-5w3h | Intuition\nSort Your given array. Why? Because we need to find subsequence so order isnt define for them.\nWe are asked to return minimum number of subsequence | JigglyyPuff | NORMAL | 2023-03-04T12:01:53.807270+00:00 | 2023-03-04T12:01:53.807299+00:00 | 340 | false | # Intuition\nSort Your given array. Why? Because we need to find subsequence so order isnt define for them.\nWe are asked to return minimum number of subsequence we need to form so our aim is to add as many number as possible in one array with limit(k).\n`How limit is defined? largest ele - Smallest ele`\nAs we sorted our array so for each subsequence the first element will be smallest and just check if by adding curr element if we are still in our limit. (The problem is reduced in finding subarrays within limit)\n`If yes -> add the element\nIf not -> add the by far collected ans in res and reset your ans as empty to start finding new subarray.`\nRes carries all the possible subsequnces thus, return its length as the min no of subsequences required.\n\n# Code\n```\nclass Solution:\n def partitionArray(self, nums: List[int], k: int) -> int:\n nums.sort()\n \n # Base Case\n if nums[-1] - nums[0] <= k:\n return 1\n\n ans = []\n ans.append(nums[0])\n res = []\n for i in range(len(nums)-1):\n if nums[i + 1] - ans[0] <= k:\n ans.append(nums[i + 1])\n else:\n res.append(ans)\n ans = []\n ans.append(nums[i + 1])\n res.append(ans)\n # print(res)\n return len(res)\n\n``` | 3 | 0 | ['Python3'] | 1 |
partition-array-such-that-maximum-difference-is-k | Two Pointers | two-pointers-by-akshat0610-7j5u | \nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) \n{\n sort(nums.begin(),nums.end());\n // 3 6 1 2 5--> 1 2 3 5 6 \n | akshat0610 | NORMAL | 2022-10-23T16:21:53.765933+00:00 | 2022-10-23T16:21:53.765970+00:00 | 499 | false | ```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) \n{\n sort(nums.begin(),nums.end());\n // 3 6 1 2 5--> 1 2 3 5 6 \n int count=0;\n int start=0;\n int end=0;\n \n while(end<nums.size())\n {\n \twhile(end<nums.size() and (nums[end]-nums[start])<=k)\n \t{\n \t\tend++;\n\t\t}\n\t\tstart=end;\n\t\tcount++;\n\t}\n\treturn count;\n}\n};\n``` | 3 | 0 | ['C', 'Sorting', 'C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | Sort CPP very easy | sort-cpp-very-easy-by-thakur6306-1bcr | class Solution {\npublic:\n int partitionArray(vector& nums, int k) {\n \n \n sort(nums.begin(),nums.end(),greater());\n int l=0; | thakur6306 | NORMAL | 2022-06-12T04:57:50.141570+00:00 | 2022-06-12T04:57:50.141613+00:00 | 47 | false | class Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n \n \n sort(nums.begin(),nums.end(),greater<int>());\n int l=0;\n int ans=0;\n // 6 5 3 2 1 0\n for(int i=1;i<nums.size();i++){\n if(nums[l]-nums[i]>k){\n ans++;\n l=i;\n }\n }\n return ans+1;\n \n }\n}; | 3 | 0 | [] | 1 |
partition-array-such-that-maximum-difference-is-k | Array with maximum k difference - Sort - Simple - Boolean | array-with-maximum-k-difference-sort-sim-8o8j | Hi,\n\nInitially I went through the thought process of figuring out the solution, Since the differenece is the main factor of grouping the items its better to s | Surendaar | NORMAL | 2022-06-05T13:46:53.349730+00:00 | 2022-06-05T13:49:18.433390+00:00 | 106 | false | Hi,\n\nInitially I went through the thought process of figuring out the solution, Since the differenece is the main factor of grouping the items its better to sort the given array in the first step itself.\n\nTo make sure the items are tracked and added I kept a boolean array to keep track of the elements. This will make sure the items are added to the resultant list.\n\nNext we can itrate through the given array, this is the crutial step which has multiple conditions to be handled.\n\nI maintained a current value which will store the differance at any point in time. If the value is greater than K then \n\t1. If the difference is greater than the given value k -> increment the result\n\t2. Increment the index everytime, because one element can\'t be shared \n\t3. One last step is to make the flag as true once element is added and check at last if the element is not added then increment the result and add to the list.\n\nHere is the my code implementing the same, Kindly upvote if it helps.. Happy learning :)\n\n```\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int res=0;\n int curr=0, i=0;\n boolean flag[] = new boolean[nums.length];\n while(i<nums.length-1){\n \tcurr = curr+nums[i+1]-nums[i];\n \tif(curr>k){\n \t\tflag[i]=true;\n \t\tcurr=0;\n \t\tres++;\n \t}\n \ti++;\n }\n if(!flag[nums.length-1])\n \tres++;\n return res;\n } | 3 | 0 | ['Sorting', 'Java'] | 0 |
partition-array-such-that-maximum-difference-is-k | Go(lang) Solution | golang-solution-by-0xedb-gbar | go\nfunc partitionArray(nums []int, k int) int {\n // remember you\'re trying to minimize difference \n // k is the ceiling\n // sort to group higher v | 0xedb | NORMAL | 2022-06-05T05:25:58.662589+00:00 | 2022-06-05T05:25:58.662628+00:00 | 60 | false | ```go\nfunc partitionArray(nums []int, k int) int {\n // remember you\'re trying to minimize difference \n // k is the ceiling\n // sort to group higher values together (to minimize difference)\n \n // then keep expanding till difference larger than k \n // create new sequence(increment) in that case\n \n sort.Ints(nums)\n \n ans := 1\n \n \n min := nums[0]\n max := nums[0]\n \n for i := 0; i < len(nums); i++ {\n max = nums[i]\n \n if (max - min) > k {\n ans++\n \n min = nums[i]\n }\n }\n \n return ans\n}\n``` | 3 | 0 | ['Go'] | 0 |
partition-array-such-that-maximum-difference-is-k | C++ || sort | c-sort-by-aniketbasu-cv9j | \nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n if(size(nums) == 1) return 1;\n sort(begin(nums),end(nums));\n | aniketbasu | NORMAL | 2022-06-05T04:01:16.593450+00:00 | 2022-06-05T04:01:16.593482+00:00 | 271 | false | ```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n if(size(nums) == 1) return 1;\n sort(begin(nums),end(nums));\n int i=1,cnt = 0;\n int minEle = nums[0];\n while(i < size(nums)){\n if(abs(minEle - nums[i]) > k){ // when the condition is not satisfied just update the min element and increase the count .\n minEle = nums[i];\n cnt++;\n }\n i++;\n }\n return cnt+1; // + 1 for the last subsequence .\n }\n};\n``` | 3 | 0 | ['C', 'Sorting', 'C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | Clean & Professional: Greedy Two-Pointer Partitioning After Sorting | clean-professional-greedy-two-pointer-pa-u31f | IntuitionThe problem asks us to minimize the number of subsequences such that the difference between the maximum and minimum element in each subsequence is less | shubhodeep_mukherjee | NORMAL | 2025-04-07T04:24:29.485441+00:00 | 2025-04-07T04:24:29.485441+00:00 | 11 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem asks us to minimize the number of subsequences such that the difference between the maximum and minimum element in each subsequence is less than or equal to <b>k</b>.
Now, here's the key insight:
If we sort the array, then in any valid subsequence, the first element will be the minimum, and the maximum difference we care about will come from comparing it with the current element as we move forward.
So, to ensure we’re creating the minimum number of subsequences, we can greedily include as many elements as possible in the current subsequence until the difference exceeds <b>k</b>. At that point, we start a new subsequence.
<b>This is a classic case where the two-pointer technique shines — efficient, clean, and optimal.</b>
# Approach
<!-- Describe your approach to solving the problem. -->
1. Sort the array to make sure the difference between any two elements in a potential subsequence can be evaluated linearly.
2. Initialize two pointers:
i → Marks the start (minimum element) of the current subsequence.
j → Scans forward to check if elements can be included in the current subsequence.
3. For every step:
If nums[j] - nums[i] <= k, we can include nums[j] in the current subsequence → move j forward.
If nums[j] - nums[i] > k, the difference has crossed the limit:
We count the current subsequence by incrementing subseq.
Reset i = j to start a new subsequence from the current element.
4. After the loop, don't forget to count the last subsequence that may not have been added yet.
5. Return the total count of subsequences.
This greedy method ensures we group as many elements as possible into one valid subsequence before starting a new one — which leads to the minimum number of partitions.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
<h3>O(nlogn)</h3>
..Sorting the array takes O(nlogn).
..The two-pointer traversal takes O(n) in the worst case, since each pointer only moves forward.
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
<h3>O(1)</h3>
We’re not using any extra space aside from a few variables.
# Code
```cpp []
class Solution {
public:
int partitionArray(vector<int>& nums, int k) {
sort(nums.begin(),nums.end());
int i=0,j=0;
int subseq=0;
while(i<nums.size() && j<nums.size()){
int diff=nums[j]-nums[i];
if(diff>k ){
i=j;
subseq++;
}
else{
j++;
}
}
subseq++;
return subseq;
}
};
``` | 2 | 0 | ['Array', 'Two Pointers', 'Greedy', 'Sorting', 'C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | Simple Beginner Java Solution(O(n*k)) | simple-beginner-java-solutiononk-by-rajn-y7nq | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1. Create a Freq to tra | rajnarayansharma110 | NORMAL | 2024-10-19T13:12:33.331241+00:00 | 2024-10-19T13:12:33.331268+00:00 | 19 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a Freq to track the count of each number in nums\n2. also keep track of max and min to decrease iterations\n3. then just count subsequece using freq and k\n# Complexity\n- Time complexity:O(n*k)\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```java []\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n int[] freq = new int[100001];\n int min = Integer.MAX_VALUE;\n int max = Integer.MIN_VALUE;\n for (int num : nums) {\n freq[num]++;\n min = Math.min(min, num);\n max = Math.max(max, num);\n }\n int subsequences = 0;\n for (int i = min; i <= max; i++) {\n if (freq[i] > 0) {\n subsequences++;\n int count = 0;\n for (int j = i; j <= i + k && j <= max; j++) {\n count += freq[j];\n freq[j] = 0;\n }\n i += k;\n }\n }\n return subsequences;\n }\n}\n\n``` | 2 | 0 | ['Java'] | 0 |
partition-array-such-that-maximum-difference-is-k | ✅💯🔥Simple Code📌🚀| 🔥✔️Easy to understand🎯 | 🎓🧠Beginner friendly🔥| O(n) Time Complexity💀💯 | simple-code-easy-to-understand-beginner-tjcgr | 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 | atishayj4in | NORMAL | 2024-07-24T20:04:29.751839+00:00 | 2024-08-01T19:19:18.427027+00:00 | 80 | 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 partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int count =1;\n int start =0;\n for(int i=1;i<nums.length;i++)\n {\n if(nums[i]-nums[start]>k)\n {\n count++;\n start =i;\n }\n }\n return count;\n }\n}\n```\n\n | 2 | 0 | ['Array', 'Greedy', 'C', 'Sorting', 'Python', 'C++', 'Java'] | 0 |
partition-array-such-that-maximum-difference-is-k | 🔥🔥✅Partition Array Such that Maximum Difference is K || Fast & Super Easy💫✅🔥🔥 | partition-array-such-that-maximum-differ-1nac | \n\n# Code\n\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end());\n int ans = 1;\ | _sinister_ | NORMAL | 2023-04-06T09:57:38.002704+00:00 | 2023-04-06T09:57:38.002747+00:00 | 202 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end());\n int ans = 1;\n int i = 0;\n int a = 0;\n int b = nums[0];\n while(i<nums.size())\n {\n a = nums[i];\n if(a>(b+k))\n {\n ans++;\n a = nums[i];\n b = nums[i];\n }\n i++;\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Array', 'Sorting'] | 1 |
partition-array-such-that-maximum-difference-is-k | 2294. Simple Multiple solutions with Explanation | Beats 96% | 2294-simple-multiple-solutions-with-expl-9e62 | \n# Approach\n- Two pointer + Greedy\nSince we want the seperations to as minimum as possible we will use greedy and check with first and last and moves on to t | ramana721 | NORMAL | 2023-03-29T14:46:19.740417+00:00 | 2023-03-29T14:46:19.740454+00:00 | 334 | false | \n# Approach\n- Two pointer + Greedy\nSince we want the seperations to as minimum as possible we will use greedy and check with first and last and moves on to the right when a possible seperation is met the counter is updated and index of right is changed to starting index of previous seperation - 1 and left is set to 0 and approach goes on till right reaches 0.\nBut sadly there are many worst case test cases so this doesn\'t work properly the next code has the same time complexity irrespective of best or worst case \n\n# Complexity\n- For this code the \n Best case : O(1)\nworst case may even go exponentially O(N^2)\n\n# Code - 1\n```\nclass Solution:\n def partitionArray(self, nums: List[int], k: int) -> int:\n nums.sort()\n n = len(nums)\n left, right = 0, n - 1\n count = 0\n if k == 0:\n new = len(set(nums))\n return new\n while right >= 0 and left <= right:\n first, second = nums[left], nums[right]\n if left == right:\n count += 1\n right -= 1\n left = 0\n continue\n if second - first <= k:\n count += 1\n left, right = 0, left - 1\n else: left += 1\n return count\n```\n# Complexity\n- TIme Complexity : O(N + Log(N))\n# Code - 2\n```\nclass Solution:\n def partitionArray(self, nums: List[int], k: int) -> int:\n cnt = 1\n nums.sort()\n start = nums[0]\n for i in range(1,len(nums)):\n if nums[i]-start <= k:\n continue\n else:\n start = nums[i]\n cnt+= 1\n return cnt\n``` | 2 | 0 | ['Array', 'Greedy', 'Sorting', 'Python3'] | 0 |
partition-array-such-that-maximum-difference-is-k | c++|| very simple & optimized | c-very-simple-optimized-by-sheetal0797-g5j6 | \n# Code\n\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int c=1,mini=INT_MAX;\n sort(nums.begin(),nums.end()); | sheetal0797 | NORMAL | 2023-02-02T05:51:57.698019+00:00 | 2023-02-02T05:51:57.698053+00:00 | 196 | false | \n# Code\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int c=1,mini=INT_MAX;\n sort(nums.begin(),nums.end());\n for(int i=0;i<nums.size();i++)\n {\n mini=min(mini,nums[i]);\n if(nums[i]-mini>k)\n {\n c++;\n mini=nums[i];\n }\n }return c;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | Java easy to understand answer | java-easy-to-understand-answer-by-ssgane-f6qs | \nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int count =1;\n int start =0;\n for(in | ssganesh035 | NORMAL | 2022-09-28T16:24:08.687865+00:00 | 2022-09-28T16:24:08.687915+00:00 | 567 | false | ```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int count =1;\n int start =0;\n for(int i=1;i<nums.length;i++)\n {\n if(nums[i]-nums[start]>k)\n {\n count++;\n start =i;\n }\n }\n return count;\n }\n}\n``` | 2 | 0 | ['Sorting', 'Java'] | 0 |
partition-array-such-that-maximum-difference-is-k | ✅ [Java/JavaScript] Simple Fast Solution || Faster Than 100% | javajavascript-simple-fast-solution-fast-xg8k | Java code:\n\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n var list = new ArrayList<Integer>();\n list.add(num | PoeticIvy302543 | NORMAL | 2022-06-07T01:15:24.561175+00:00 | 2022-07-25T21:32:52.721007+00:00 | 226 | false | Java code:\n```\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n var list = new ArrayList<Integer>();\n list.add(nums[0]);\n var count = 0;\n for (int i = 1; i < nums.length; i++) {\n if (nums[i]-list.get(0)>k) {\n count++;\n list = new ArrayList<>();\n }\n list.add(nums[i]);\n }\n if (!list.isEmpty()) {\n count++;\n }\n return count;\n }\n```\n\nJavaScript code:\n```\nvar partitionArray = function(nums, k) {\n let sorted = nums.sort((a, b) => a-b)\n let list = []\n let count = 0\n list.push(sorted[0])\n for (i = 1; i < sorted.length; i++) {\n let num = sorted[i]\n if (num-list[0]>k) {\n count++\n list = []\n }\n list.push(num)\n } if (list.length) count++\n return count\n\n};\n``` | 2 | 0 | ['Sorting', 'Java', 'JavaScript'] | 0 |
partition-array-such-that-maximum-difference-is-k | Javascript || Easy understanding | javascript-easy-understanding-by-ciciyu8-ywnr | \nvar partitionArray = function(nums, k) {\n nums.sort((a,b)=>a-b)\n var start = 0;\n var end = 0;\n var count = 0;\n \n while(start<nums.length){\n | ciciYu8472 | NORMAL | 2022-06-05T17:22:44.356368+00:00 | 2022-06-05T17:22:44.356413+00:00 | 112 | false | ```\nvar partitionArray = function(nums, k) {\n nums.sort((a,b)=>a-b)\n var start = 0;\n var end = 0;\n var count = 0;\n \n while(start<nums.length){\n var diff = nums[end]-nums[start]\n if(diff<=k){\n end++;\n }\n else {\n count++;\n start = end;\n }\n } return count\n};\n``` | 2 | 0 | ['JavaScript'] | 0 |
partition-array-such-that-maximum-difference-is-k | C++ Easy and Simplest Solution Using Sorting | c-easy-and-simplest-solution-using-sorti-c4g1 | Step 1: We will sort the array in non-decreasing order.\nStep 2: Mark the starting position and iterate through array and whenever the diference of starting ind | wa_survivor | NORMAL | 2022-06-05T10:22:59.880691+00:00 | 2022-06-05T10:22:59.880745+00:00 | 149 | false | Step 1: We will sort the array in non-decreasing order.\nStep 2: Mark the starting position and iterate through array and whenever the diference of starting index and cuurent index exceeds k this means we have to start a new subsequence.\nStep 3: Returning the number of subsequences in which we have to split.\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int count=1;\n int start=0;\n for(int i=1;i<nums.size();i++){\n if(nums[i]-nums[start]>k){\n start=i;\n count++;\n }\n }\n return count;\n }\n};\n``` | 2 | 0 | ['Array', 'Greedy', 'Sorting'] | 1 |
partition-array-such-that-maximum-difference-is-k | 100% faster solution using sort and upper_bound | 100-faster-solution-using-sort-and-upper-ozui | Upper bound function return iterator of just greater element of searching element. \nso first of all sort the given vector and using it - nums.begin() calculate | akash_nita | NORMAL | 2022-06-05T08:45:27.321147+00:00 | 2022-06-05T08:45:27.321189+00:00 | 55 | false | Upper bound function return iterator of just greater element of searching element. \nso first of all sort the given vector and using **it - nums.begin()** calculate the next element that can be part of subsequence and do untill upper bound return **nums.end()** \nand use a counter that will count our answer and simply return it whenever its completed \n\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n \n \n int ans=0;\n int i=0,temp=nums[0]+k;\n while(i<nums.size()){\n auto it=upper_bound(nums.begin(),nums.end(),temp);\n i=it-nums.begin();\n ans++;\n if(it==nums.end())return ans;\n temp=nums[i]+k;\n \n }\n \n return ans;\n }\n};****\n```\n\n**please... Upvote :)** | 2 | 0 | ['C', 'Sorting', 'C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | ✅C++ Easy to understand clean code with comments | c-easy-to-understand-clean-code-with-com-x9r7 | It has been asked that we need to partition the array such that the difference of the maximum and the minimum values of the individual partition do not exceed a | Shubham-Bhardwaj | NORMAL | 2022-06-05T07:41:14.941671+00:00 | 2022-06-05T07:41:14.941702+00:00 | 44 | false | It has been asked that we need to partition the array such that the difference of the maximum and the minimum values of the individual partition do not exceed a certain value `k `. \n\nIt is clear that we need to keep track of the **minimum** and **maximum** value of the partition. But if we **sort** the array beforehand, the first value would be the minimum and last value would be maximum. \n\nThen we loop through the array, checking at each step that we take that if the difference of maximum and minimum exceeds k, if it does, a new partion is formed with present element as the new minimum.\n\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int i,j,count=1; // initially the whole array is a single partition, hence count=1\n sort(nums.begin(), nums.end()); // sort the whole array\n\t\t\n for(i=0; i<nums.size();){\n for(j=i; j<nums.size(); j++){\n\t\t\t\t// i is the index of present minimum, j is the index of present maximum\n if(nums[j]-nums[i] > k){ \n count++;\n break;\n }\n }\n i=j; // present element becomes the new minimum\n }\n\t\t\n return count;\n }\n};\n``` | 2 | 0 | ['C', 'Sorting', 'C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | Sort Array|Java| O(nlogn) time | sort-arrayjava-onlogn-time-by-shradha199-hcpd | The idea is to sort the array.\n- If the array is sorted, we know that the smallest element would be at left end and largest at the right end of the sorted arra | shradha1994 | NORMAL | 2022-06-05T05:16:49.609873+00:00 | 2022-06-05T05:22:46.306228+00:00 | 78 | false | - The idea is to sort the array.\n- If the array is sorted, we know that the smallest element would be at left end and largest at the right end of the sorted array.\n - Thus, to get the difference between minimum and maximum element, we can just find the difference between the first and last element of the sorted array.\n \n The algorithm can be described as,\n - Find the sum of first and last element of sorted array,\n\t 1. If the difference is less than or equal to k, we no longer need to divide the subarray further.\n\t 2. If the difference is greater than k, we will have to divide the current array into subarrays. \n\t The trick is that, we have to divide the current array such that the difference between largest and smallest element is less than the current difference. We can do this by pickup up next smaller element.\n\n```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int result = 1;\n int end = nums.length - 1;\n int lastPartition = 0;\n \n for(int left = 0;left<nums.length;left++){\n int difference = nums[end] - nums[left];\n if(difference <= k)\n return result;\n if(nums[left] - nums[lastPartition] > k || lastPartition == left){\n result += 1;\n lastPartition = left;\n } \n }\n return result;\n \n }\n}\n``` | 2 | 0 | [] | 1 |
partition-array-such-that-maximum-difference-is-k | [Java] Sort + Sliding Window | With Explanation | java-sort-sliding-window-with-explanatio-1wj2 | Steps\n1. sort the array\n2. for each element:\n2.1. update the min & max\n2.2. if max - min > k, counter++ and reset the min & max\n3. counter++ for the last | visonli | NORMAL | 2022-06-05T04:58:00.190859+00:00 | 2022-06-05T05:15:26.447855+00:00 | 40 | false | ### Steps\n1. sort the array\n2. for each element:\n2.1. update the min & max\n2.2. if max - min > k, counter++ and reset the min & max\n3. counter++ for the last one sequence\n\n### Complexity\ntime: `O(nlogn)`\nspace: `O(logn or n)` depends on the sorting algorithm\n\n### Java\n```java\npublic int partitionArray(int[] A, int k) {\n int n = A.length, res = 0, min = A[0], max = A[0];\n Arrays.sort(A);\n\n for (int i = 0; i < n; i++) {\n min = Math.min(min, A[i]);\n max = Math.max(max, A[i]);\n\n if (max - min > k) {\n res++;\n min = max = A[i];\n }\n }\n return res + 1;\n}\n``` | 2 | 0 | [] | 1 |
partition-array-such-that-maximum-difference-is-k | Python Easy Understanding | python-easy-understanding-by-rnyati2000-cn6d | Here the most basic idea is to first sort the array , coz then it will become an easy ques as comapred to medium coz now u only have to traverse through the lis | rnyati2000 | NORMAL | 2022-06-05T04:43:50.709780+00:00 | 2022-06-05T04:43:50.709827+00:00 | 143 | false | Here the most basic idea is to first sort the array , coz then it will become an easy ques as comapred to medium coz now u only have to traverse through the list at once which will only take O(n) time complexity coz then we just have to compare the min value of the curent list with the current value and if we get that difference greater than k , then we just create a new list and keep on working on this concept and we will always get minimum no of lists only.\n```\nclass Solution:\n def partitionArray(self, nums: List[int], k: int) -> int:\n nums.sort()\n l=[[nums[0]]]\n for i in range(1,len(nums)):\n if nums[i]-l[-1][0]<=k:\n l[-1].append(nums[i])\n \n else:\n l.append([nums[i]])\n \n return len(l)\n```\nIf u understood the code then plz.......UPVOTE.......Thnx in adv | 2 | 0 | ['Python'] | 2 |
partition-array-such-that-maximum-difference-is-k | Javascript | javascript-by-umeshiscreative-snig | Sort the array\n- Select maximum diff of max element - min element\nIf difference > k then only increase count and make start of another subsequence as ith elem | umeshiscreative | NORMAL | 2022-06-05T04:35:25.626747+00:00 | 2022-06-05T04:35:52.503759+00:00 | 36 | false | - Sort the array\n- Select maximum diff of max element - min element\nIf difference > k then only increase count and make start of another subsequence as ith element.\n```\n\nlet Partition_Array_Such_That_Maximum_Difference_Is_K = function (nums, k) {\n nums.sort((a, b) => a - b);\n let minV = nums[0];\n let count = 1;\n for (let i = 1; i < nums.length; i++) {\n let diff = nums[i] - minV;\n if (diff > k) {\n count++;\n minV = nums[i];\n }\n }\n return count;\n};\n``` | 2 | 0 | [] | 0 |
partition-array-such-that-maximum-difference-is-k | c++ solution using sorting | c-solution-using-sorting-by-dilipsuthar6-2e3m | \nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end());\n int n=nums.size();\n | dilipsuthar17 | NORMAL | 2022-06-05T04:01:52.165878+00:00 | 2022-06-05T04:01:52.165914+00:00 | 124 | false | ```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end());\n int n=nums.size();\n int count=1;\n int mn=nums[0];\n int mx=nums[0];\n for(int i=1;i<n;i++)\n {\n mn=min(nums[i],mn);\n mx=max(nums[i],mx);\n if(mx-mn<=k)\n {\n continue;\n }\n else\n {\n count++;\n mn=nums[i];\n mx=nums[i];\n }\n }\n return count;\n }\n};\n``` | 2 | 0 | ['C', 'C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | Sorting | Java | sorting-java-by-aaveshk-utsj | \nclass Solution\n{\n public int partitionArray(int[] nums, int k)\n {\n int count = 1;\n int min = 100001, max = -1;\n Arrays.sort(n | aaveshk | NORMAL | 2022-06-05T04:01:19.586451+00:00 | 2022-06-05T04:01:19.586489+00:00 | 152 | false | ```\nclass Solution\n{\n public int partitionArray(int[] nums, int k)\n {\n int count = 1;\n int min = 100001, max = -1;\n Arrays.sort(nums);\n for(int i = 0 ;i < nums.length; i++)\n {\n max = Math.max(max,nums[i]);\n min = Math.min(min,nums[i]);\n if(max - min > k)\n {\n count++;\n min = max; // The new substring has just one element which is max and min both\n }\n }\n return count;\n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
partition-array-such-that-maximum-difference-is-k | 0ms 100% O(N) No sort | 0ms-100-on-no-sort-by-michelusa-orfd | Sorting works but is O(N log N)We can exploit the problem constraints by making use of a "bucket ordering".Time complexity: O(N)Code | michelusa | NORMAL | 2025-04-10T23:32:09.832871+00:00 | 2025-04-10T23:32:09.832871+00:00 | 4 | false | Sorting works but is O(N log N)
We can exploit the problem constraints by making use of a "bucket ordering".
Time complexity: O(N)
# Code
```cpp []
class Solution {
public:
int partitionArray(std::vector<int>& nums, int k) {
std::array<bool, 100001> exist = {};
int min_val = nums[0];
int max_val = nums[0];
for (int num : nums) {
min_val = std::min(min_val, num);
max_val = std::max(max_val, num);
exist[num] = true;
}
if (max_val - min_val <= k) {
return 1;
}
int count_subsequences = 1;
int cur_min = nums[0];
int start = min_val;
for (int i = min_val; i <= max_val; ++i) {
if (exist[i]) {
if (i - start > k) {
++count_subsequences;
start = i;
}
}
}
return count_subsequences;
}
};
``` | 1 | 0 | ['C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | || SOLUTION FOR MY REFERENCE || | solution-for-my-reference-by-ujjwalvarma-csc8 | Code | ujjwalvarma6948 | NORMAL | 2025-01-30T03:17:06.095787+00:00 | 2025-01-30T03:17:06.095787+00:00 | 45 | false |
# Code
```cpp []
class Solution {
public:
int partitionArray(vector<int>& nums, int k) {
sort(nums.begin(),nums.end());
int count=0;
int i=0;
while(i<nums.size()){
count++;
int start=nums[i];
while(i<nums.size() and nums[i]-start<=k){
i++;
}
}
return count;
}
};
``` | 1 | 0 | ['C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | Partition Array Such That Maximum Difference Is K | partition-array-such-that-maximum-differ-afo1 | Intuition\nThe problem is about partitioning an array into the minimum number of subsets such that the difference between the maximum and minimum element in eac | tejdekiwadiya | NORMAL | 2024-11-26T11:56:08.883705+00:00 | 2024-11-26T11:56:08.883732+00:00 | 29 | false | # Intuition\nThe problem is about partitioning an array into the minimum number of subsets such that the difference between the maximum and minimum element in each subset is at most ( k ). The first idea is to sort the array so that elements with smaller differences are adjacent, which makes grouping them easier.\n\n# Approach\n1. **Sort the Array**: Sorting ensures that elements closer in value are adjacent. This minimizes the chances of missing valid groups.\n2. **Initialize Variables**: Use `count` to track the number of subsets required and `idx` to point to the start of the current subset.\n3. **Iterate through the Array**:\n - Start from the second element.\n - If the difference between the current element (`nums[i]`) and the first element of the current subset (`nums[idx]`) exceeds ( k ), increment the subset count and update `idx` to the current index (`i`).\n4. **Return the Count**: The final value of `count` will be the number of subsets.\n\n# Complexity\n- **Time Complexity**: \n - Sorting the array takes ( O(n log n) ).\n - The iteration through the array is ( O(n) ).\n - Overall complexity: ( O(n log n) ).\n\n- **Space Complexity**:\n - Sorting requires ( O(log n) ) space for the sorting algorithm (or ( O(n) ) depending on the implementation).\n - Overall complexity: ( O(1) ) additional space since no other significant space is used apart from variables.\n\n# Code\n```java []\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int count = 1;\n int idx = 0;\n for (int i = 1; i < nums.length; i++) {\n if (nums[i] - nums[idx] > k) {\n count++;\n idx = i;\n }\n }\n return count;\n }\n}\n``` | 1 | 0 | ['Array', 'Greedy', 'Sorting', 'Java'] | 0 |
partition-array-such-that-maximum-difference-is-k | Extend within Range | extend-within-range-by-mdsrrkhan-x5yl | \n\n# Code\njava []\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int max = nums[0]+k;\n int | mdsrrkhan | NORMAL | 2024-09-14T19:26:45.003949+00:00 | 2024-09-14T19:26:45.003978+00:00 | 4 | false | \n\n# Code\n```java []\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int max = nums[0]+k;\n int count = 0;\n int left = 1;\n while(left<nums.length){\n if(nums[left]<=max)\n left++;\n else{\n count++;\n max = nums[left]+k;\n }\n }\n return count+1;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
partition-array-such-that-maximum-difference-is-k | ✅ The way you beat 🔥 100% of users 🔥 | the-way-you-beat-100-of-users-by-nguyenl-o92n | Intuition\n Describe your first thoughts on how to solve this problem. \nJust use a hash table.\n\n# Approach\n Describe your approach to solving the problem. \ | nguyenlinh1993 | NORMAL | 2023-11-22T15:33:15.232686+00:00 | 2023-11-22T15:33:33.991802+00:00 | 10 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust use a hash table.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Step 1**: Find the `min` and `max` values of `nums`\n\n**Step 2**: Create `a hash table` to sort the values of nums\n\n**Step 3**: The init point is `start` and from the `min` value. Because the `max - min <= k` (from the subsequence array), we loop each time `start = start + k`. The purpose is to split nums by using a hash table.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(3*n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n int max = 0, min = Integer.MAX_VALUE, ans = 0;\n for (int x : nums) {\n max = Math.max(max, x);\n min = Math.min(min, x);\n }\n int[] a = new int[max + 1];\n for (int x : nums) {\n a[x] = 1;\n }\n int start = min;\n while (start <= max) {\n ans++;\n start += k + 1;\n while (start <= max && a[start] == 0) {\n start++;\n }\n }\n\n return ans;\n }\n}\n``` | 1 | 0 | ['Hash Table', 'Java'] | 0 |
partition-array-such-that-maximum-difference-is-k | C++ | O(1) space complexity | c-o1-space-complexity-by-princesah999-khnx | Complexity\n- Time complexity: O(N logN)\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\ | Princesah999 | NORMAL | 2023-09-17T22:09:52.039566+00:00 | 2023-09-17T22:09:52.039586+00:00 | 526 | false | # Complexity\n- Time complexity: O(N logN)\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 partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int mini = nums[0], cnt = 0;\n for(int it: nums){\n if(it-mini > k){\n cnt++; mini = it;\n }\n }\n return cnt+1;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | First Binary search solution on Leetcode | first-binary-search-solution-on-leetcode-pn1w | Approach\nJust think of minimization problem of binary search.\n# Complexity\n- Time complexity:\nO(nlogn) ->nlog(n) due to sorting\n\n- Space complexity:\nO(1) | Harsh6350 | NORMAL | 2023-09-03T14:13:16.631968+00:00 | 2023-09-03T14:13:50.433225+00:00 | 307 | false | # Approach\nJust think of minimization problem of binary search.\n# Complexity\n- Time complexity:\nO(n*logn) ->n*log(n) due to sorting\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n // int partitionArray(vector<int>& nums, int k) {\n int chck(vector<int>&v1,int k,int md)\n {\n int cnt=1,n=v1.size(),maxi=INT_MIN,mini=INT_MAX;\n for(int i=0;i<n;i++)\n {\n maxi=max(maxi,v1[i]);\n mini=min(mini,v1[i]);\n if((maxi-mini)>k)\n {\n maxi=v1[i],mini=v1[i];\n cnt++;\n }\n }\n return cnt;\n\n }\n\n int partitionArray(vector<int>& v1, int k) {\n sort(v1.begin(),v1.end());\n \n int l=1,h=1e9,ans=INT_MAX;\n\n while(l<=h)\n {\n \n int md=(l+h)/2;\n if(ans>=chck(v1,k,md))\n {\n ans=chck(v1,k,md);\n }\n else\n break;\n \n h=md-1;\n }\n \n return ans;\n }\n};\n``` | 1 | 0 | ['Binary Search', 'Sorting', 'C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | greedy approach | greedy-approach-by-harishchandra8384-imc4 | Intuition\nsorting and two pointer\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. | harishchandra8384 | NORMAL | 2023-07-16T09:54:11.129482+00:00 | 2023-07-16T09:54:11.129505+00:00 | 9 | false | # Intuition\nsorting and two pointer\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 partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n int n = nums.size();\n int i =0, j=0;\n int count = 1;\n while( j<n){\n int z = nums[j]- nums[i];\n if(z<=k){\n j++;\n }\n else{\n i =j;\n count++;\n }\n }\n return count;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
partition-array-such-that-maximum-difference-is-k | C++ | Easy to Understand with Comments! | c-easy-to-understand-with-comments-by-ch-cgn0 | 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 | charucjoshi | NORMAL | 2023-06-16T11:39:49.749270+00:00 | 2023-06-16T11:39:49.749291+00:00 | 21 | 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 partitionArray(vector<int>& nums, int k) {\n int ans = 1; //There will be atleast one such partition\n //start denotes the starting point of the partition\n //end denotes the ending point\n int start = 0, end = 0;\n \n //Sort and start traversing\n sort(nums.begin(),nums.end());\n while(end < nums.size()){\n if(nums[end]-nums[start] <= k){\n //If valid check for the next index\n end++;\n }\n else{\n //If invalid then move start to this index\n start = end;\n ans++;\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | ✅✅ Easy C++ Solution 😎😎 | easy-c-solution-by-deepak_5910-6e0s | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nSort the array and appl | Deepak_5910 | NORMAL | 2023-05-27T06:53:55.741606+00:00 | 2023-05-27T06:53:55.741638+00:00 | 12 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSort the array and apply this approach, **how many elements can be push between minimum and maximum.**\n\n# Complexity\n- Time complexity: O(N*logN)\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 partitionArray(vector<int>& arr, int k) {\n sort(arr.begin(),arr.end());\n\n int n = arr.size();\n\n int mn = arr[0];\n int mx = arr[0];\n\n int ans = 1;\n\n for(int i = 0;i<n;i++)\n {\n mx = arr[i];\n if(mx-mn>k)\n {\n mn = arr[i];\n ans++;\n }\n }\n\n return ans;\n }\n};\n``` | 1 | 0 | ['Greedy', 'Sorting', 'C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | c++ solution | c-solution-by-lakshita17-2ay0 | \n\n# Code\n\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int count =0;\n | Lakshita17 | NORMAL | 2023-05-22T12:18:44.578888+00:00 | 2023-05-22T12:18:44.578926+00:00 | 17 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int count =0;\n int i=0; int j=0;\n while(j<nums.size()){\n if(abs(nums[i]-nums[j])<=k){\n j++;\n }\n else{\n count++;\n i=j;\n }\n }\n\n return count+1;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | java code | java-code-by-emotional_ashish-brck | 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 | emotional_ashish | NORMAL | 2023-05-10T07:01:35.966916+00:00 | 2023-05-10T07:01:35.966954+00:00 | 12 | 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 partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int ans=1;\n int i=0, j=0;\n while(j<nums.length){\n if(i==j){\n j++;\n continue;\n }\n if(nums[j]-nums[i]<=k){\n j++;\n }\n else{\n ans++;\n i=j;\n }\n }\nreturn ans;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
partition-array-such-that-maximum-difference-is-k | Two Pointer Solution || CPP || O(1) Space | two-pointer-solution-cpp-o1-space-by-skp-28vj | 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 | skp10092001 | NORMAL | 2023-04-01T20:29:16.667467+00:00 | 2023-04-01T20:29:16.667500+00:00 | 761 | 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\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int count=0;\n int min=0;\n int max=0;\n while(max<nums.size())\n {\n if(abs(nums[max]-nums[min])<=k)\n {\n max++;\n }\n else\n {\n count++;\n min=max;\n }\n }\n return count+1;\n }\n};\n``` | 1 | 0 | ['Two Pointers', 'C++'] | 1 |
partition-array-such-that-maximum-difference-is-k | Simple and Easy | Sorting and greedy | Beginner Friendly | simple-and-easy-sorting-and-greedy-begin-8n7w | 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 | armangupta48 | NORMAL | 2023-02-02T18:09:33.915926+00:00 | 2023-02-02T18:09:33.915968+00:00 | 627 | 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 partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int st = 0;\n int count =0;\n for(int i = 0;i<nums.size();i++)\n {\n if(nums[i]-nums[st]<=k)\n {\n if(i == nums.size()-1)\n {\n count++;\n }\n continue;\n }\n else\n {\n count++;\n st = i;\n i--;\n }\n\n }\n return count;\n }\n};\n``` | 1 | 0 | ['Greedy', 'C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | C++✅✅| 200ms Faster than 90%🔥 | Easy Approach | Clean & Concise Code | | c-200ms-faster-than-90-easy-approach-cle-ojd4 | \n# Code\n\n\nclass Solution {\npublic:\n\n int partitionArray(vector<int>& nums, int k) {\n \n sort(nums.begin(),nums.end());\n\n int r | mr_kamran | NORMAL | 2022-12-09T04:59:05.024395+00:00 | 2022-12-09T04:59:47.426979+00:00 | 179 | false | \n# Code\n```\n\nclass Solution {\npublic:\n\n int partitionArray(vector<int>& nums, int k) {\n \n sort(nums.begin(),nums.end());\n\n int res = 1; n = nums.size(), mini = nums[0];\n\n for(int i = 0; i < n; ++i)\n {\n if((nums[i] - mini) > k)\n {\n res++;\n mini = nums[i];\n }\n }\n\n return res;\n }\n};\n\n\n``` | 1 | 0 | ['C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | C++ Solution Using Sorting And Map | c-solution-using-sorting-and-map-by-lotu-8v2w | Code\n\nclass Solution \n{\npublic:\n int partitionArray(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end());\n int n=nums.size() | lotus18 | NORMAL | 2022-11-30T07:13:08.092513+00:00 | 2022-11-30T07:13:08.092586+00:00 | 12 | false | # Code\n```\nclass Solution \n{\npublic:\n int partitionArray(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end());\n int n=nums.size();\n map<int,int> m;\n for(int x=0; x<n; x++) m[nums[x]]=x;\n int division=0;\n int i=0;\n while(i<n)\n {\n for(int x=nums[i]+k; x>=nums[i]; x--)\n {\n if(m.find(x)!=m.end()) \n {\n division++;\n i=m[x]+1;\n break;\n }\n }\n }\n return division;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
partition-array-such-that-maximum-difference-is-k | C++|| ✅✅ || Easy to Understand || 5-6 Line code | c-easy-to-understand-5-6-line-code-by-aa-dllb | class Solution {\npublic:\n\n int partitionArray(vector& nums, int k) {\n \n int j = 0;\n int ans = 1; \n \n \n s | aatiqAFZAL | NORMAL | 2022-11-15T16:53:58.089665+00:00 | 2022-11-15T16:53:58.089707+00:00 | 170 | false | class Solution {\npublic:\n\n int partitionArray(vector<int>& nums, int k) {\n \n int j = 0;\n int ans = 1; \n \n \n sort(nums.begin(), nums.end(), greater<int>());\n \n \n for(int i=1; i<nums.size(); i++){\n \n if(nums[j]- nums[i] > k){\n ans++;\n j = i;\n }\n }\n \n return ans;\n \n }\n}; | 1 | 0 | ['C'] | 0 |
partition-array-such-that-maximum-difference-is-k | [JAVA] easy solution on sorting | java-easy-solution-on-sorting-by-juganta-i7qs | \n# Code\n\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int res = 1, mn = nums[0], mx = nums[0];\n | Jugantar2020 | NORMAL | 2022-11-14T16:12:39.240385+00:00 | 2022-11-14T16:12:39.240423+00:00 | 14 | false | \n# Code\n```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int res = 1, mn = nums[0], mx = nums[0];\n for (int a : nums) {\n mn = Math.min(mn, a);\n mx = Math.max(mx, a);\n if (mx - mn > k) {\n res ++;\n mn = mx = a;\n }\n }\n return res; \n }\n}\n```\n# PLEASE UPVOTE IF IT WAS HELPFULL | 1 | 0 | ['Java'] | 0 |
partition-array-such-that-maximum-difference-is-k | c++|easy solution|sorting | ceasy-solutionsorting-by-agrutsav-uykl | ```\nclass Solution {\npublic:\n int partitionArray(vector& nums, int k) {\n sort(nums.begin(),nums.end());\n int cnt=0;\n int j=0;\n | agrutsav | NORMAL | 2022-11-14T14:00:32.128724+00:00 | 2022-11-14T14:00:32.128750+00:00 | 434 | false | ```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int cnt=0;\n int j=0;\n for(int i=1;i<nums.size();i++)\n {\n if(nums[i]-nums[j]>k){\n cnt++;\n j=i;\n }\n }\n cnt++;\n return cnt;\n }\n}; | 1 | 0 | ['C', 'Sorting'] | 0 |
partition-array-such-that-maximum-difference-is-k | Java brute force easy solution O(nlogn) | java-brute-force-easy-solution-onlogn-by-z159 | Code\n\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int count = 1;\n int start=nums[0];\n | Adilwaris | NORMAL | 2022-09-30T21:33:20.266024+00:00 | 2022-09-30T21:33:40.034784+00:00 | 268 | false | # Code\n```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int count = 1;\n int start=nums[0];\n for(int i=0;i<nums.length;i++){\n if(nums[i]-start>k){\n start=nums[i];\n count++;\n } \n }return count;\n }\n} \n``` | 1 | 0 | ['Array', 'Java'] | 0 |
partition-array-such-that-maximum-difference-is-k | Java sort clean solution | java-sort-clean-solution-by-superman-qia-mo0w | \nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int res = 0;\n int range = -1;\n for(i | Superman-Qiang | NORMAL | 2022-09-23T02:59:11.388790+00:00 | 2022-09-23T02:59:11.388826+00:00 | 98 | false | ```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int res = 0;\n int range = -1;\n for(int i =0;i<nums.length;i++){\n if(nums[i]<=range) continue;\n else{\n range = nums[i]+k;\n res++;\n }\n }\n return res;\n }\n}\n``` | 1 | 0 | ['Sorting', 'Java'] | 0 |
partition-array-such-that-maximum-difference-is-k | C++ Sorting Binary search easy | c-sorting-binary-search-easy-by-harshthe-41m7 | \nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n \n sort(nums.begin(),nums.end());\n \n int ans=0;\n | harshtheman0011 | NORMAL | 2022-09-14T09:56:42.096775+00:00 | 2022-09-14T09:56:42.096818+00:00 | 74 | false | ```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n \n sort(nums.begin(),nums.end());\n \n int ans=0;\n int j=0;\n while(j<nums.size())\n {\n auto i=upper_bound(nums.begin(),nums.end(),nums[j]+k);\n int index=int(i-nums.begin());\n \n ans++;\n j=index;\n }\n \n return ans;\n }\n};\n``` | 1 | 0 | ['Greedy', 'C', 'Sorting', 'Binary Tree'] | 0 |
partition-array-such-that-maximum-difference-is-k | Java Simple and Short Solution | 88% memory | With Explanation | java-simple-and-short-solution-88-memory-pobx | \n```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int count = 1;\n int start = nums[0];\n\ | tbekpro | NORMAL | 2022-09-13T07:08:30.667856+00:00 | 2022-09-13T07:08:30.667897+00:00 | 34 | false | \n```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int count = 1;\n int start = nums[0];\n\t\t//for each iteration I find difference between first element of subsequence\n\t\t//and current element. If difference is > than k, then I just increment subsequence count\n\t\t//and make current element as start element for the next subsequence\n for (int i = 1; i < nums.length; i++) {\n if (nums[i] - start > k) {\n count++;\n start = nums[i];\n }\n }\n return count;\n }\n} | 1 | 0 | [] | 0 |
partition-array-such-that-maximum-difference-is-k | C++ Solution | c-solution-by-valarmorghulis8620-i3pk | ```\nclass Solution {\npublic:\n int partitionArray(vector& nums, int k) {\n sort(nums.begin(),nums.end()); \n int maxi= INT_MIN; int mini= INT | ValarMorghulis8620 | NORMAL | 2022-09-02T14:21:44.589976+00:00 | 2022-09-02T14:21:44.590023+00:00 | 55 | false | ```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end()); \n int maxi= INT_MIN; int mini= INT_MAX; int count=0; int n=nums.size();\n for(int i=0;i<n;i++)\n {\n mini= min(mini,nums[i]);\n maxi=max(maxi, nums[i]);\n if(maxi-mini <=k)\n continue;\n else\n {\n count++;\n maxi=INT_MIN;\n mini= INT_MAX;\n i--;\n } \n }\n return count+1;\n }\n}; | 1 | 0 | ['Sorting'] | 0 |
partition-array-such-that-maximum-difference-is-k | sorting, easy, 2 pointer | sorting-easy-2-pointer-by-amanp2517-aiqv | class Solution {\npublic:\n int partitionArray(vector& nums, int k) {\n sort(nums.begin(),nums.end());\n int cnt=1;\n int i=0,j=1;\n | amanp2517 | NORMAL | 2022-08-08T19:27:12.124645+00:00 | 2022-08-08T19:27:12.124675+00:00 | 25 | false | class Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int cnt=1;\n int i=0,j=1;\n while(j<nums.size())\n {\n if (nums[j]-nums[i]<=k)\n {\n j++;\n }\n else\n {\n cnt++;\n i=j;\n }\n \n \n }\n return cnt;\n }\n}; | 1 | 0 | ['Two Pointers', 'Sorting'] | 0 |
partition-array-such-that-maximum-difference-is-k | Java || Explained ||Two Approach || use one loop | java-explained-two-approach-use-one-loop-o4n6 | \n\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums); // we sort the array so it will be easy for us to track \n | Sharad21 | NORMAL | 2022-07-17T21:19:46.205669+00:00 | 2022-07-17T21:19:54.530797+00:00 | 34 | false | ```\n\n```class Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums); // we sort the array so it will be easy for us to track \n int count=1;\n int start=0;//for the smallest number\n for(int i=0;i<nums.length;i++){\n \n //basically if the diff b/w smallest and larget number is greater \n //than k then we do change the minimum and \n //shift the numbwe into new subsequence and +1 the count;\n if(nums[i]-nums[start]>k){\n start=i;\n count++;\n }\n // if(nums[i]-nums[start]<=k){\n // continue;\n // }else{\n // start=i;\n // count++;\n // }\n }\n return count;\n }\n}\n//kindly upvote if you find it helpful | 1 | 0 | [] | 0 |
partition-array-such-that-maximum-difference-is-k | Python3 O(n) min-max blocks counts | python3-on-min-max-blocks-counts-by-atm1-f5x1 | \nclass Solution:\n def partitionArray(self, nums: List[int], k: int) -> int:\n nums.sort()\n res=1\n minm=nums[0]\n maxm=nums[0] | atm1504 | NORMAL | 2022-07-15T18:43:24.581391+00:00 | 2022-07-15T18:43:24.581438+00:00 | 228 | false | ```\nclass Solution:\n def partitionArray(self, nums: List[int], k: int) -> int:\n nums.sort()\n res=1\n minm=nums[0]\n maxm=nums[0]\n for x in nums:\n if abs(x-minm)>k or abs(x-maxm)>k:\n res+=1\n minm=x\n maxm=x\n else:\n minm=min(minm,x)\n maxm=max(maxm,x)\n return res\n \n``` | 1 | 0 | ['Sorting', 'Python', 'Python3'] | 1 |
partition-array-such-that-maximum-difference-is-k | 60% TC and 78% SC easy python solution using binary search | 60-tc-and-78-sc-easy-python-solution-usi-o66t | \ndef partitionArray(self, nums: List[int], k: int) -> int:\n\tans = 0\n\tnums.sort()\n\ti = 0\n\twhile(i < len(nums)):\n\t\ti = bisect_right(nums, nums[i]+k, i | nitanshritulon | NORMAL | 2022-07-14T15:23:51.902189+00:00 | 2022-07-14T15:23:51.902235+00:00 | 134 | false | ```\ndef partitionArray(self, nums: List[int], k: int) -> int:\n\tans = 0\n\tnums.sort()\n\ti = 0\n\twhile(i < len(nums)):\n\t\ti = bisect_right(nums, nums[i]+k, i)\n\t\tans += 1\n\treturn ans\n``` | 1 | 0 | ['Greedy', 'Binary Tree', 'Python', 'Python3'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.