question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
split-the-array | Scala one-liner | scala-one-liner-by-hariprasath1436-z4fa | Explanation\n- nums.groupBy(identity): This groups the elements of the array nums based on their identity, effectively creating a map where the keys are the dis | hariprasath1436 | NORMAL | 2024-02-25T06:13:18.617881+00:00 | 2024-02-25T06:13:18.617911+00:00 | 23 | false | # Explanation\n- nums.groupBy(identity): This groups the elements of the array nums based on their identity, effectively creating a map where the keys are the distinct elements of nums and the values are arrays containing occurrences of those elements.\n\n- .mapValues(_.length): For each group (value) in the map, this maps it to its length, effectively giving the count of occurrences of each distinct element in nums.\n\n- .values: This extracts the values (counts) from the map.\n\n- .forall(_ < 3): This checks whether all the counts in the values satisfy the condition that they are less than 3. The forall method returns true if all elements in the collection satisfy the specified predicate (in this case, being less than 3), and false otherwise.\n\n# Code\n```\nobject Solution {\n def isPossibleToSplit(nums: Array[Int]): Boolean = {\n nums.groupBy(identity).mapValues(_.length).values.forall( _ < 3)\n\n }\n}\n``` | 2 | 0 | ['Scala'] | 0 |
split-the-array | Easiest Simple 5 -- different ways C // C++ // Python3 // Java // Python Beats 100% | easiest-simple-5-different-ways-c-c-pyth-9960 | Intuition\n\n\n\nC++ []\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n unordered_map<int, int> mp;\n for (auto& x : | Edwards310 | NORMAL | 2024-02-25T05:04:22.003168+00:00 | 2024-02-25T05:04:22.003199+00:00 | 58 | false | # Intuition\n\n\n\n```C++ []\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n unordered_map<int, int> mp;\n for (auto& x : nums)\n mp[x]++;\n for (auto& pr : mp) {\n if (pr.second > 2)\n return false;\n }\n return true;\n }\n};\n```\n```python3 []\nclass Solution:\n def isPossibleToSplit(self, nums: List[int]) -> bool:\n map = {}\n for num in nums:\n map[num] = map.get(num, 0) + 1\n\n for cnt in map.values():\n if cnt > 2:\n return False\n return True\n```\n```C []\nbool isPossibleToSplit(int* nums, int numsSize) {\n int* arr = (int*)malloc(sizeof(int) * 101);\n for (int i = 0; i < 101; ++i)\n arr[i] = 0;\n for (int i = 0; i < numsSize; ++i) {\n arr[nums[i]]++;\n if (arr[nums[i]] > 2)\n return false;\n }\n return true;\n}\n```\n```Java []\nclass Solution {\n public boolean isPossibleToSplit(int[] nums) {\n Arrays.sort(nums);\n for (int i = 2; i < nums.length; ++i) {\n if (nums[i] == nums[i - 2])\n return false;\n }\n return true;\n }\n}\n```\n```python []\nclass Solution(object):\n def isPossibleToSplit(self, nums):\n """\n :type nums: List[int]\n :rtype: bool\n """\n ele_freq = [0] * 101\n\n for num in nums:\n ele_freq[num] += 1\n if ele_freq[num] > 2:\n return False\n \n return True\n```\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```\nclass Solution:\n def isPossibleToSplit(self, nums: List[int]) -> bool:\n map = {}\n for num in nums:\n map[num] = map.get(num, 0) + 1\n\n for cnt in map.values():\n if cnt > 2:\n return False\n return True\n\n``` | 2 | 0 | ['Array', 'Hash Table', 'C', 'Python', 'C++', 'Java', 'Python3'] | 0 |
split-the-array | Java Weekly Challenge | java-weekly-challenge-by-shree_govind_je-welq | Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n)\n Add your space complexity here, e.g. O(n) \n\n# Code | Shree_Govind_Jee | NORMAL | 2024-02-25T04:55:23.025466+00:00 | 2024-02-25T04:55:23.025485+00:00 | 55 | false | # Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isPossibleToSplit(int[] nums) {\n Map<Integer, Integer> map = new HashMap<>();\n for (int num : nums) {\n map.put(num, map.getOrDefault(num, 0) + 1);\n }\n\n for (var key : map.keySet()) {\n if (map.get(key) > 2)\n return false;\n }\n return true;\n }\n}\n``` | 2 | 0 | ['Hash Table', 'Hash Function', 'Java'] | 0 |
split-the-array | Using Hash Map | Simple and Easy | Python | using-hash-map-simple-and-easy-python-by-s7gm | Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n\nclass Solution:\n def isPossibleToSplit(self, nums: List[int]) -> bool:\n | pragya_2305 | NORMAL | 2024-02-25T04:19:21.464641+00:00 | 2024-02-25T04:19:21.464664+00:00 | 136 | false | # Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def isPossibleToSplit(self, nums: List[int]) -> bool:\n count = Counter(nums)\n \n for val in count.values():\n if val>2:\n return False\n return True\n``` | 2 | 0 | ['Hash Table', 'Python', 'Python3'] | 1 |
split-the-array | Full Intution From Scratch(You Won't Regret) C++ | full-intution-from-scratchyou-wont-regre-5ciw | Intuition\n###### <- As given in the question that nums is an array of even length,you have to split it into two parts such that they are equal in terms of leng | unvisitedNode_01 | NORMAL | 2024-02-25T04:04:33.490389+00:00 | 2024-02-27T08:27:54.916249+00:00 | 180 | false | # Intuition\n###### <- As given in the question that nums is an array of even length,you have to split it into two parts such that they are equal in terms of length and each part length will be (original length of array/2) (ofcourse becuase original array length is even so we can split it into two equal parts of same length n/2)\n#### One thing that I know for sure that in order to divide the array in n/2 parts i have to take all the elements that are present in the original array means i cannot skip any element\n###### Now second condition is that i have to divide it in such a way that each part contains distinct or unique element that means we cant repeat the number in same part however if the number is in two different parts that is okay\n\n##### Now think when i will not be able to split ,ofcourse when the given condition will become wrong and when will that happen ,when a part will not have distinct element means it will have two or more element of same type in the same part\n\n###### Now when this condition will happen ,when there are more than 2 elements in the original array of same type, so we forcefully need to put same type element more than once in same part that will break the condition and we will not be able to split the array\n###### So we just need to check if the freq of all the elements in original array is less than equal to 2 if yes then it is true otherwise it will be false>\nFor checking freq whats the best way :-Hashmap \n\n# Approach\n##### <Take a unordered map and save all the freq of all elements from original array then check if any element has freq greater than 2 if yes return false else return true\n\n# Complexity\n- Time complexity:\n<o(n)>\n\n- Space complexity:\n<o(n)->\n\n# Code\n```\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n unordered_map<int,int>k;\n for(int i=0;i<nums.size();i++){\n k[nums[i]]++;\n }\n for(int i=0;i<nums.size();i++){\n if(k[nums[i]]>2){\n return false;\n }\n }\n return true;\n }\n};\n\n\n```\nUPVOTE :) | 2 | 0 | ['Hash Table', 'C++'] | 0 |
split-the-array | ☑️✅Easy JAVA Solution || Beats 100%✅☑️ | easy-java-solution-beats-100-by-vritant-2dk1w | Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n)\n Add your space complexity here, e.g. O(n) \n\n# Code | vritant-goyal | NORMAL | 2024-02-25T04:03:52.499276+00:00 | 2024-02-25T04:03:52.499313+00:00 | 121 | false | # Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isPossibleToSplit(int[] nums) {\n int n=nums.length;\n HashMap<Integer,Integer>map=new HashMap<>();\n int count=0;\n for(int i=0;i<n;i++){\n map.put(nums[i],map.getOrDefault(nums[i],0)+1);\n }\n for(int it:map.values()){\n if(it>2)return false;\n }\n return true;\n }\n}``` | 2 | 0 | ['Java'] | 1 |
split-the-array | Pigeon Hole Principle | pigeon-hole-principle-by-kevinujunior-zo4w | Intuition\n Suppose we have m pigeons and n holes where m>n and we want to put m pigeons into n holes, then atleast one hole will have more than one pigeon. \n | kevinujunior | NORMAL | 2024-02-25T04:03:02.937360+00:00 | 2024-02-25T04:09:30.964556+00:00 | 101 | false | # Intuition\n* Suppose we have m pigeons and n holes where m>n and we want to put m pigeons into n holes, then atleast one hole will have more than one pigeon. \n* Similarly, if we have a number with frequency > 2 and we want to put this number into one of the 2 arrays then atleast one array will have the duplicate number.\n\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n int n = nums.size();\n unordered_map<int,int> mp;\n \n for(auto i:nums){\n mp[i]++;\n if(mp[i]>2) return false;\n }\n \n return true;\n \n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
split-the-array | Java Solution Map | java-solution-map-by-devanshi_bilthare-dkzk | 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 | Devanshi_Bilthare | NORMAL | 2024-02-25T04:03:02.727345+00:00 | 2024-02-25T04:03:02.727367+00:00 | 50 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\n public boolean isPossibleToSplit(int[] nums) {\n Map<Integer,Integer> map = new HashMap<>();\n int n = nums.length;\n for(int i =0;i < n;i++){\n map.put(nums[i],map.getOrDefault(nums[i],0)+1);\n }\n \n for (int freq : map.values()) {\n if(freq > 2)return false;\n }\n \n \n return true;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
split-the-array | C++ 100% Fast | Easy Step By Step Explanation | c-100-fast-easy-step-by-step-explanation-3r0y | Intuition\n1. Frequency Counting: The problem revolves around determining if elements in the array can be divided into two halves with distinct elements. This s | VYOM_GOYAL | NORMAL | 2024-02-25T04:02:39.449973+00:00 | 2024-02-25T04:02:39.449995+00:00 | 169 | false | # Intuition\n1. **Frequency Counting:** The problem revolves around determining if elements in the array can be divided into two halves with distinct elements. This suggests using a data structure to track element frequencies.\n2. **Unique Element Requirement:** The key constraint is that each element can appear at most twice in the entire array to allow for distinct halves.\n\n# Approach\n1. **Count Frequencies:** Use a unordered_map to efficiently count the occurrences of each element in nums.\n2. **Check for Impossible Cases:**\n - If the number of unique elements is less than half the array length, it\'s impossible to form distinct halves.\n - If any element appears more than twice, it cannot be placed in distinct halves.\n3. **Return Splitting Possibility:** If no impossible cases are encountered, a valid split is possible.\n\n# Complexity\n- Time complexity: **O(n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(n)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n unordered_map<int, int>mp;\n for(auto it:nums){\n mp[it]++;\n }\n int unique = mp.size();\n for(auto it:mp){\n if(it.second>2){\n return false;\n }\n }\n return true;\n }\n};\n```\n\n\n | 2 | 0 | ['Array', 'Ordered Map', 'C++'] | 0 |
split-the-array | ☑️ Splitting the Array. ☑️ | splitting-the-array-by-abdusalom_16-jrb0 | Code | Abdusalom_16 | NORMAL | 2025-04-06T12:05:37.378664+00:00 | 2025-04-06T12:05:37.378664+00:00 | 15 | false | # Code
```dart []
class Solution {
bool isPossibleToSplit(List<int> nums) {
nums.sort((a, b) => a.compareTo(b));
List<int> list1 = [];
List<int> list2 = [];
for(int i = 0; i < nums.length; i++){
if(!list1.contains(nums[i]) && list1.length <= list2.length){
list1.add(nums[i]);
}else{
if(!list2.contains(nums[i])){
list2.add(nums[i]);
}else{
return false;
}
}
}
if(list1.length == list2.length){
return true;
}
print(list1);
print(list2);
return false;
}
}
``` | 1 | 0 | ['Array', 'Hash Table', 'Counting', 'Dart'] | 0 |
split-the-array | Using HashMap = easy | using-hashmap-easy-by-sairangineeni-c252 | IntuitionStep 1: Count the frequency of each number in nums using a HashMap.
Step 2: Check if any number appears more than twice. If yes, return false.
Step 3: | Sairangineeni | NORMAL | 2025-02-28T08:13:30.542979+00:00 | 2025-02-28T08:13:30.542979+00:00 | 143 | false | # Intuition
Step 1: Count the frequency of each number in nums using a HashMap.
Step 2: Check if any number appears more than twice. If yes, return false.
Step 3: If the number of unique elements is at least nums.length / 2, return true; otherwise, return false.
# Code
```java []
class Solution {
public static boolean isPossibleToSplit(int[] nums) {
HashMap<Integer, Integer>hm = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
hm.put(nums[i], hm.getOrDefault(nums[i], 0)+1);
}
for(Integer a : hm.keySet()) {
if(hm.get(a) > 2) {
return false;
}
}
return true;
}
}
``` | 1 | 0 | ['Java'] | 0 |
split-the-array | Easy C++ aproach - frequency | easy-c-aproach-frequency-by-ju5t1natcodi-nofj | IntuitionWe can only have distinct numbers if their frequency is at most 2, because if it is at least 3, than at least one of the arrays will have at least 2 eq | Ju5t1natcoding | NORMAL | 2025-02-19T19:54:50.628685+00:00 | 2025-02-19T19:54:50.628685+00:00 | 52 | false | # Intuition
We can only have distinct numbers if their frequency is at most 2, because if it is at least 3, than at least one of the arrays will have at least 2 equal elements. Therefore, we count the numbers frequency and constantly check if their frequency is at least 3 or not.
# Approach
Create an array in which we save the frequency of each element from the array. After that, check the frequency for every element.
You can also use a hash map instead of an array, but, for me at least, it took more memory than by using an array.
# Complexity
- Time complexity: ***O(n)***
- Space complexity: ***O(101) ~ O(1)***
# Code
```cpp []
class Solution {
public:
bool isPossibleToSplit(vector<int>& nums) {
vector<int> fr(101);
for (int i = 0; i < nums.size(); ++i) {
fr[nums[i]]++;
if(fr[nums[i]] > 2)
return false;
}
return true;
}
};
``` | 1 | 0 | ['C++'] | 0 |
split-the-array | Counter is the !!KEY!! Beats 100% + Beginner Friendly :) | counter-is-the-key-beats-100-beginner-fr-7kbm | IntuitionThe problem requires us to split the given array into two parts such that both contain distinct elements. The key observation is that if any number app | lil77 | NORMAL | 2025-02-17T07:49:36.668226+00:00 | 2025-02-17T07:49:36.668226+00:00 | 84 | false | 
# Intuition
The problem requires us to split the given array into two parts such that both contain distinct elements. The key observation is that if any number appears more than twice, it becomes impossible to distribute it between the two subarrays while keeping both distinct.
# Approach
- ### 1. Count the occurrences of each number in nums using Counter().
- ### 2. If any number appears more than twice, return False, since it would be impossible to distribute it while maintaining distinct elements in both halves.
- ### 3. Otherwise, return True, as we can always split the array into two valid halves.
# Complexity
- Time complexity: O(n)
- Space complexity: O(n)
# Code
```python3 []
class Solution:
def isPossibleToSplit(self, nums: List[int]) -> bool:
counter = Counter(nums)
for value in counter.values():
if value > 2:
return False
return True
```
# Show Some Love Please if You Like :) | 1 | 0 | ['Python3'] | 0 |
split-the-array | Solution in Java and C | solution-in-java-and-c-by-vickyy234-g8tx | Code | vickyy234 | NORMAL | 2025-02-12T04:46:51.886298+00:00 | 2025-02-12T04:46:51.886298+00:00 | 127 | false | # Code
```java []
class Solution {
public boolean isPossibleToSplit(int[] nums) {
int len = nums.length;
int[] freq = new int[101];
for (int i = 0; i < len; i++) {
freq[nums[i]]++;
if (freq[nums[i]] > 2) {
return false;
}
}
return true;
}
}
```
```C []
bool isPossibleToSplit(int* nums, int numsSize) {
int freq[101] = {'0'};
for (int i = 0; i < numsSize; i++) {
freq[nums[i]]++;
if (freq[nums[i]] > 2) {
return false;
}
}
return true;
}
``` | 1 | 0 | ['Array', 'C', 'Counting', 'Java'] | 0 |
split-the-array | Easiest Solution in Java | easiest-solution-in-java-by-sathurnithy-cuom | Code | Sathurnithy | NORMAL | 2025-02-11T05:49:57.999149+00:00 | 2025-02-11T05:49:57.999149+00:00 | 126 | false | # Code
```java []
class Solution {
public boolean isPossibleToSplit(int[] nums) {
int[] freq = new int[101];
for (int value : nums) {
if (freq[value]++ >= 2)
return false;
}
return true;
}
}
``` | 1 | 0 | ['Array', 'Counting', 'Java'] | 0 |
split-the-array | Easiest Solution in C | easiest-solution-in-c-by-sathurnithy-xbdp | Code | Sathurnithy | NORMAL | 2025-02-11T05:45:55.812306+00:00 | 2025-02-11T05:45:55.812306+00:00 | 26 | false | # Code
```c []
bool isPossibleToSplit(int* nums, int numsSize) {
int freq[101] = {0};
for (int i = 0; i < numsSize; i++) {
freq[nums[i]]++;
if (freq[nums[i]] > 2)
return false;
}
return true;
}
``` | 1 | 0 | ['Array', 'C', 'Counting'] | 0 |
split-the-array | C++ Simple and Short, Using Hashmap, 0 ms Beats 100% | c-simple-and-short-using-hashmap-0-ms-be-69s0 | Code\ncpp []\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n unordered_map<int, int> freq;\n for (auto n : nums) {\n | yehudisk | NORMAL | 2024-11-25T13:26:46.431744+00:00 | 2024-11-25T13:26:46.431782+00:00 | 73 | false | # Code\n```cpp []\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n unordered_map<int, int> freq;\n for (auto n : nums) {\n if (freq[n] == 2) return false;\n freq[n]++;\n }\n return true;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
split-the-array | Easy to understand | easy-to-understand-by-abhinav_bal-9nct | \n\n# Code\npython []\nclass Solution(object):\n def isPossibleToSplit(self, nums):\n """\n :type nums: List[int]\n :rtype: bool\n | Abhinav_Bal | NORMAL | 2024-11-16T16:24:31.672871+00:00 | 2024-11-16T16:24:31.672909+00:00 | 17 | false | \n\n# Code\n```python []\nclass Solution(object):\n def isPossibleToSplit(self, nums):\n """\n :type nums: List[int]\n :rtype: bool\n """\n unique_elements = len(set(nums))\n n = len(nums)\n if unique_elements < n // 2:\n return False\n \n for i in range(n):\n count=0\n for j in range(n):\n if nums[i]==nums[j]:\n count+=1\n if count>2:\n return False\n \n else:\n return True\n \n``` | 1 | 0 | ['Python'] | 0 |
split-the-array | Solution using hashmap 100% beat | solution-using-hashmap-100-beat-by-cs_22-469h | \n# Complexity\n- Time complexity:O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(N)\n Add your space complexity here, e.g. O(n) \n\n# | CS_2201640100153 | NORMAL | 2024-11-07T05:44:49.961614+00:00 | 2024-11-07T05:44:49.961653+00:00 | 27 | false | \n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def isPossibleToSplit(self, nums: List[int]) -> bool:\n if len(nums)%2!=0:\n return False\n d={}\n for i in nums:\n if i in d:\n d[i]+=1\n else:\n d[i]=1\n for i,j in d.items():\n if j>2:\n return False\n return True\n \n``` | 1 | 0 | ['Array', 'Hash Table', 'Counting', 'Python3'] | 0 |
split-the-array | Friendly & Clear | friendly-clear-by-anevil-3555 | Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(N)\n Add your space complexity here, e.g. O(n) \n\n# Code\ncsharp []\npublic class Solution {\n | Anevil | NORMAL | 2024-10-09T12:45:53.108020+00:00 | 2024-10-09T12:45:53.108051+00:00 | 15 | false | # Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```csharp []\npublic class Solution {\n public bool IsPossibleToSplit(int[] nums) \n {\n var nums1 = new HashSet<int>();\n var nums2 = new HashSet<int>();\n\n foreach(var num in nums)\n {\n if (nums1.Add(num) || nums2.Add(num))\n {\n continue;\n }\n\n return false;\n }\n\n return true;\n }\n}\n``` | 1 | 0 | ['C#'] | 0 |
split-the-array | Check If Splitting is Possible with Frequency Constraint Using C++ | check-if-splitting-is-possible-with-freq-3vef | Intuition\nThe first step to determine if the array can be split is to ensure that no element appears more than twice, as this would violate the conditions for | Krishnaa2004 | NORMAL | 2024-09-07T17:56:34.221639+00:00 | 2024-09-07T17:56:34.221659+00:00 | 244 | false | # Intuition\nThe first step to determine if the array can be split is to ensure that no element appears more than twice, as this would violate the conditions for a valid split.\n\n# Approach\n- Traverse the array and use an unordered map to count the frequency of each element.\n- If any element appears more than twice, return `false`.\n- If all elements meet the condition, return `true`.\n\n# Complexity\n- **Time complexity:** $$O(n)$$, where $$n$$ is the length of the array. We traverse the array once.\n- **Space complexity:** $$O(n)$$, since we use a map to store the frequency of each element.\n\n# Code\n```cpp\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n unordered_map<int, int> m; \n for(auto i = nums.begin(); i != nums.end(); ++i) {\n m[*i]++; \n if(m[*i] > 2) {\n return false; \n }\n }\n return true; \n }\n};\n```\n | 1 | 0 | ['C++'] | 0 |
split-the-array | Easy Solution || Beginner Friendly✔✔✔ || Easy Concept ☠☠☠ | easy-solution-beginner-friendly-easy-con-xs57 | 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 | ahnnikmisra | NORMAL | 2024-07-24T16:42:19.560501+00:00 | 2024-07-24T16:42:19.560526+00:00 | 17 | false | # 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 public boolean isPossibleToSplit(int[] nums) {\n java.util.Arrays.sort(nums);\n int curr = nums[0];\n int count = 1;\n for(int i = 1 ; i < nums.length ; i++)\n {\n if(nums[i] == curr)\n {\n count++;\n }\n else\n {\n count = 1;\n curr = nums[i];\n }\n if(count > 2)\n {\n return false;\n }\n }\n return true; \n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
split-the-array | Using Map Easy Approach | using-map-easy-approach-by-shikhar_4s-w4wk | 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 | Shikhar_4s | NORMAL | 2024-07-20T20:48:47.023745+00:00 | 2024-07-20T20:48:47.023762+00:00 | 158 | 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 bool isPossibleToSplit(vector<int>& nums) {\n unordered_map<int,int>m;\n for(int i=0;i<nums.size();i++){\n m[nums[i]]++;\n }\n for(int i=0;i<nums.size();i++){\n if(m[nums[i]]>2)return false;\n }\n \n return true;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
split-the-array | Simple java solution | simple-java-solution-by-kramprakash2005-09we | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind the solution provided is to sort the array nums. After sorting, if | kramprakash2005 | NORMAL | 2024-06-20T08:14:49.236868+00:00 | 2024-06-20T08:14:49.236904+00:00 | 8 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind the solution provided is to sort the array nums. After sorting, if there exists any element in the sorted array such that it is equal to the element two positions ahead of it (nums[i] == nums[i+2]), then it\'s not possible to split the array as required. This is because if such a pair exists, it means there are at least two identical elements within any three consecutive elements in the sorted array, making it impossible to separate them into two distinct groups without having elements from one group equal to elements from the other group.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) Sorting: Sort the array nums. Sorting helps in easily identifying consecutive elements.\n2) Checking Consecutive Triplets: Iterate through the sorted array and check if nums[i] is equal to nums[i+2]. If such a condition is found, return false immediately because the array cannot be split as required.\n3) Return True: If no such consecutive triplet is found where nums[i] == nums[i+2], return true, indicating it is possible to split the array as required.\n\n# Complexity\n- Time complexity:O(n log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isPossibleToSplit(int[] nums) {\n int n=nums.length;\n Arrays.sort(nums);\n for(int i=0;i<n-2;i++){\n if(nums[i]==nums[i+2]) return false;\n }\n return true;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
split-the-array | Simple C Solution (frequency method) 100% | simple-c-solution-frequency-method-100-b-u5ho | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1. find if any number a | rajnarayansharma110 | NORMAL | 2024-04-08T18:08:52.910425+00:00 | 2024-04-08T18:08:52.910458+00:00 | 22 | 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. find if any number appear more then twice\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nbool isPossibleToSplit(int* a, int n) {\n int freq[101]={0};\n for(int i=0;i<n;i++){\n freq[a[i]]++;\n if(freq[a[i]]>2){\n return false;\n }\n }\n // for(int i=0;i<101;i++){\n // if(freq[i]>2){\n // return false;\n // }\n // }\n return true;\n}\n``` | 1 | 0 | ['C'] | 0 |
split-the-array | The easiest possible solution (i think*) 😂UPVOTE IF IT HELPED MEANS A LOT TO ME TYYY 💜 | the-easiest-possible-solution-i-think-up-25e0 | Intuition\n Describe your first thoughts on how to solve this problem. \nLet\'s say we have an array that has n2+1 numbers in it. For anyone that actually knows | marzex | NORMAL | 2024-03-30T16:46:04.196655+00:00 | 2024-03-30T16:46:04.196678+00:00 | 80 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLet\'s say we have an array that has n*2+1 numbers in it. For anyone that actually knows basic maths this would be a dead giveaway that an array with that size cannot be divided into 2 seperate arrays such that their sizes are equal. So we return "false" for all the arrays that fit this if statement: if(nums.size() %2 == 1). After we get rid of all the arrays that have an odd size we move on to the real problem. We also have to make sure each array only consists of distinct/ unique numbers so that means that in the initial nums array there can\'t be more than 2 of the same number. We also need to make sure our for loop doesn\'t go ut of bounds so initialize i to 1. and finally we check if the number before and the number after our i are the same number as out nums[i]. If so we can return true, because that means in at least 1 of the 2 arrays we will have 2 of the same number. And if i gets to the end of the array without returning false, we return true since that means we can form 2 seperate arrays with distinct numbers and equal sizes. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nLet\'s say we have an array that has n*2+1 numbers in it. For anyone that actually knows basic maths this would be a dead giveaway that an array with that size cannot be divided into 2 seperate arrays such that their sizes are equal. So we return "false" for all the arrays that fit this if statement: if(nums.size() %2 == 1). After we get rid of all the arrays that have an odd size we move on to the real problem. We also have to make sure each array only consists of distinct/ unique numbers so that means that in the initial nums array there can\'t be more than 2 of the same number. We also need to make sure our for loop doesn\'t go ut of bounds so initialize i to 1. and finally we check if the number before and the number after our i are the same number as out nums[i]. If so we can return true, because that means in at least 1 of the 2 arrays we will have 2 of the same number. And if i gets to the end of the array without returning false, we return true since that means we can form 2 seperate arrays with distinct numbers and equal sizes. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n log n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(log n)\n# Code\n```\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n sort(nums.begin(), nums.end()); // sorts the vector to make it a lot easier for us :/\n if(nums.size() %2 == 1) return false; // if the size is odd return false\n for(int i = 1; i < nums.size()-1; i++) if(nums[i] == nums[i-1] && nums[i] == nums[i+1]) return false; // if the previus and the next number are the same as the ith number we return false since that prvents us from making 2 arrays with only distinct numbers\n return true;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
split-the-array | simple and using dictionary 89.22 % Time and 95.66 % Space | simple-and-using-dictionary-8922-time-an-mlwc | Intuition\nThe intuition behind solving this problem is to iterate through the given list of integers and keep track of the count of occurrences of each element | Umarulshahin | NORMAL | 2024-03-28T10:54:59.980974+00:00 | 2024-03-28T10:54:59.980991+00:00 | 38 | false | # Intuition\nThe intuition behind solving this problem is to iterate through the given list of integers and keep track of the count of occurrences of each element. If any element appears more than twice, it indicates that it is not possible to split the list into two parts such that each part contains the same number of occurrences of each integer.\n# Approach\nIn this approach, we use a dictionary to keep track of the count of occurrences of each element in the list. We iterate through the list of integers, and for each element, we check if it exists in the dictionary. If it does, we increment its count; otherwise, we initialize its count to 1. If at any point, the count of any element becomes greater than 2, we return False, indicating that it is not possible to split the list as required. Otherwise, if all elements occur at most twice, we return True.\n# Complexity\n- Time complexity:\nThe time complexity of this approach is O(n), where n is the length of the input list nums. This is because we iterate through the list once, and for each element, the dictionary operations (checking if an element exists and updating its count) are constant time operations.\n- Space complexity:\nThe space complexity is O(n) in the worst case, where n is the number of unique elements in the input list nums. This is because in the worst case, each distinct element in the list will be stored in the dictionary, along with its count. However, if the range of integers in the input list is limited, the space complexity can be considered closer to O(1).\n# Code\n```\nclass Solution:\n def isPossibleToSplit(self, nums: List[int]) -> bool:\n a={}\n for i in nums:\n if i in a:\n a[i]+=1\n else:\n a[i]=1\n if a[i]>2:\n return False\n return True\n``` | 1 | 0 | ['Python3'] | 1 |
split-the-array | Easy to understand || 100% Faster || Ruby | easy-to-understand-100-faster-ruby-by-ya-xlqg | 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 | yashwardhan24_sharma | NORMAL | 2024-03-19T09:51:18.489022+00:00 | 2024-03-19T09:51:18.489054+00:00 | 90 | 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# @param {Integer[]} nums\n# @return {Boolean}\ndef is_possible_to_split(nums)\n hash = {}\n nums.each do |i|\n if(hash[i])\n hash[i]+=1\n else\n hash[i]=1\n end\n end\n \n hash.each do |key,val|\n if(val>2)\n return false\n end\n end\n\n return true\nend\n``` | 1 | 0 | ['Ruby'] | 0 |
split-the-array | Easy Solution with Hash Table || C++ || Java || Python | easy-solution-with-hash-table-c-java-pyt-16sv | Intuition\n Describe your first thoughts on how to solve this problem. \nCount the frequency of the element in the array! if any element exist more then twice r | mahfuz2411 | NORMAL | 2024-03-11T11:38:11.299804+00:00 | 2024-03-11T11:38:11.299839+00:00 | 69 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCount the frequency of the element in the array! if any element exist more then twice return false! Otherwise return true;\n\n# Approach\nCounting, Hash Table\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Codes\n<details>\n<summary>Click here to see C++ Code</summary>\n\n```c++\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n unordered_map <int, int> m;\n for(auto d: nums) {\n m[d]++;\n if(m[d]==3) return false;\n }\n return true;\n }\n};\n```\n</details>\n<details>\n <summary>Click here to see Java Code</summary>\n\n```java\nclass Solution {\n public boolean isPossibleToSplit(int[] nums) {\n HashMap<Integer, Integer> map = new HashMap<>();\n for (int num : nums) {\n map.put(num, map.getOrDefault(num, 0) + 1);\n if (map.get(num) == 3) return false;\n }\n return true;\n }\n}\n```\n</details>\n<details>\n<summary>Click here to see Python3 Code</summary>\n\n```python\nclass Solution(object):\n def isPossibleToSplit(self, nums):\n m = {}\n for num in nums:\n m[num] = m.get(num, 0) + 1\n if m[num] == 3:\n return False\n return True\n\n```\n</details>\n\n# For any query don\'t forget to comment below! Otherwise please Upvote\uD83D\uDE0A | 1 | 0 | ['Array', 'Hash Table', 'Counting', 'Python', 'C++', 'Java'] | 0 |
split-the-array | SOLUTION | solution-by-kodiac1-j1s5 | Intuition\nthis solution is based on counting the frequencies of elements inside the array\n\n# Approach\nthe solution comprises of 3 cases \ntake two variables | Kodiac1 | NORMAL | 2024-03-06T07:48:21.917171+00:00 | 2024-03-06T07:48:21.917203+00:00 | 72 | false | # Intuition\nthis solution is based on counting the frequencies of elements inside the array\n\n# Approach\nthe solution comprises of 3 cases \ntake two variables size1 and size2 and initialise them to 0\n**case 1**-> if the frequency of any element is greater than 2 ,then that element will defenitly repeat in the other two arrays so directly return false.\n**case 2**-> if the frequency of element is 2 then both size1 and size2 would be increased simultaneously.\n**case 3**->if the frequency is 1 them whichever size1 or size2 is smaller it would be increased by 1.\nafter that compare size1 and size2.\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n int n=nums.size();\n map<int,int>mp;\n for(int i=0;i<n;i++){\n mp[nums[i]]++;\n }\n int size1=0;\n int size2=0;\n for(auto it:mp){\n if(it.second>2){\n return false;\n }\n else if(it.second==2){\n size1++;\n size2++;\n }\n else if(it.second==1){\n if(size1>size2){\n size2++;\n }\n else{\n size1++;\n }\n }\n }\n return size1==size2;\n }\n};\n``` | 1 | 0 | ['Hash Table', 'Counting', 'C++'] | 0 |
split-the-array | Simple Beginner friendly C++ Code | Beats 90 % users | simple-beginner-friendly-c-code-beats-90-fm34 | Intuition\n Describe your first thoughts on how to solve this problem. \nif a number occurs 2 times we can insert each in 2 array but if it occurs more than 2 t | srajyavardhan12 | NORMAL | 2024-03-01T02:07:40.840117+00:00 | 2024-03-01T02:07:40.840149+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nif a number occurs 2 times we can insert each in 2 array but if it occurs more than 2 times than atleast one of the splited array will have duplicate value, so we will simple count freq of each element\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums)\n {\n ios_base::sync_with_stdio(false);\n vector<int> freq(101,0);\n \n for(int i = 0; i < nums.size(); i++)\n {\n freq[nums[i]]++;\n }\n for(int i = 0; i < freq.size(); i++)\n {\n if(freq[i] >= 3)\n return false;\n }\n return true;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
split-the-array | Ruby one-liner | ruby-one-liner-by-dnnx-kc1r | \ndef is_possible_to_split(nums) = nums.tally.values.max <= 2 \n | dnnx | NORMAL | 2024-02-29T21:52:22.133015+00:00 | 2024-02-29T21:52:22.133042+00:00 | 8 | false | ```\ndef is_possible_to_split(nums) = nums.tally.values.max <= 2 \n``` | 1 | 0 | ['Ruby'] | 0 |
split-the-array | Ruby 1-line Simple Solution | ruby-1-line-simple-solution-by-vladhilko-fubh | Code\n\n# @param {Integer[]} nums\n# @return {Boolean}\ndef is_possible_to_split(nums)\n nums.tally.all? { _2 <= 2 }\nend\n | vladhilko | NORMAL | 2024-02-29T15:06:43.186474+00:00 | 2024-02-29T15:06:43.186555+00:00 | 9 | false | # Code\n```\n# @param {Integer[]} nums\n# @return {Boolean}\ndef is_possible_to_split(nums)\n nums.tally.all? { _2 <= 2 }\nend\n``` | 1 | 0 | ['Ruby'] | 1 |
split-the-array | Easy-Peasy C++ Solution 🙌🙌 | easy-peasy-c-solution-by-jasneet_aroraaa-hjgg | Code\n\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n unordered_map<int, int> hash;\n for (int i = 0; i < nums.size | jasneet_aroraaa | NORMAL | 2024-02-25T13:21:30.901859+00:00 | 2024-02-25T13:22:35.382702+00:00 | 51 | false | # Code\n```\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n unordered_map<int, int> hash;\n for (int i = 0; i < nums.size(); i++) {\n hash[nums[i]]++;\n if (hash[nums[i]] > 2) return false;\n }\n return true;\n }\n};\n``` | 1 | 0 | ['Math', 'Counting', 'Iterator', 'Hash Function', 'C++'] | 0 |
split-the-array | 1-line Linq | 1-line-linq-by-3s_akb-36wa | \n# Code\n\npublic class Solution {\n public bool IsPossibleToSplit(int[] nums) {\n return nums.GroupBy(x => x).All(x => x.Count() <= 2);\n }\n}\n | 3S_AKB | NORMAL | 2024-02-25T10:51:43.273341+00:00 | 2024-02-25T10:51:43.273366+00:00 | 37 | false | \n# Code\n```\npublic class Solution {\n public bool IsPossibleToSplit(int[] nums) {\n return nums.GroupBy(x => x).All(x => x.Count() <= 2);\n }\n}\n``` | 1 | 0 | ['C#'] | 0 |
split-the-array | Easy To Understand C++ Solution || (Using Map)✅✅ | easy-to-understand-c-solution-using-map-3bqon | Code\n\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n int n=nums.size();\n unordered_map<int,int> mp;\n if(n | Abhi242 | NORMAL | 2024-02-25T07:07:39.406283+00:00 | 2024-02-25T07:07:39.406312+00:00 | 93 | false | # Code\n```\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n int n=nums.size();\n unordered_map<int,int> mp;\n if(n%2!=0){\n return false;\n }\n for(int i=0;i<n;i++){\n mp[nums[i]]++;\n }\n for(auto a: mp){\n if(a.second>2){\n return false;\n }\n }\n return true;\n }\n};\n``` | 1 | 0 | ['Hash Table', 'C++'] | 0 |
split-the-array | Easy Solution || Beats 100%🔥💥 | easy-solution-beats-100-by-eraofkaushik0-lb7r | \n\n\n# Code\n\nclass Solution:\n def isPossibleToSplit(self, nums: List[int]) -> bool:\n c = Counter(nums)\n for i in c:\n if c[i] | EraOfKaushik003 | NORMAL | 2024-02-25T06:43:25.887258+00:00 | 2024-02-25T06:43:25.887310+00:00 | 9 | false | \n\n\n# Code\n```\nclass Solution:\n def isPossibleToSplit(self, nums: List[int]) -> bool:\n c = Counter(nums)\n for i in c:\n if c[i] > 2:\n return False\n return True\n``` | 1 | 0 | ['Hash Table', 'Counting', 'Python3'] | 0 |
split-the-array | Simple C++ | simple-c-by-deva766825_gupta-pdz5 | 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 | deva766825_gupta | NORMAL | 2024-02-25T04:59:22.031774+00:00 | 2024-02-25T04:59:22.031797+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isPossibleToSplit(vector<int>& nums) {\n int n = nums.size();\n unordered_map<int,int> map;\n for(int i=0;i<n;i++){\n map[nums[i]]++;\n }\n for(auto it : map){\n if(it.second>2)\n {\n return false;\n }\n \n }\n return true;\n \n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
split-the-array | Day-4 | day-4-by-maahigarg-eyhy | IntuitionEach number in nums should appear at most twice total(Once for the first array,Once for the second array).If any number appears 3 times or more, it's i | MaahiGarg | NORMAL | 2025-04-10T18:05:12.700962+00:00 | 2025-04-10T18:05:12.700962+00:00 | 1 | false | # Intuition
Each number in nums should appear at most twice total(Once for the first array,Once for the second array).If any number appears 3 times or more, it's impossible to split without duplicates.
# Approach
Using hash map, we count the frequency of each element and if it is greater than 2 then return false else return true.
# Complexity
- Time complexity:O(n)
- Space complexity:O(n)
# Code
```cpp []
#include <map>
class Solution {
public:
bool isPossibleToSplit(vector<int>& nums) {
std::unordered_map<int, int> freq;
for (int num : nums) {
freq[num]++;
if (freq[num] > 2) {
return false;
}
}
return true;
}
};
``` | 0 | 0 | ['C++'] | 0 |
split-the-array | ok | ok-by-akshay____p-m2v7 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Akshay____P | NORMAL | 2025-04-07T06:02:49.663296+00:00 | 2025-04-07T06:02:49.663296+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums
* @return {boolean}
*/
var isPossibleToSplit = function(nums) {
nums.sort((a,b)=>a-b);
for(let i= 0;i<nums.length-2;i++){
if(nums[i]==nums[i+2]){
return false;
}
}
return true;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
split-the-array | 3046. Split the Array | Java | HashMap | 3046-split-the-array-java-hashmap-by-_aj-50m6 | Code | _Ajit_Singh_ | NORMAL | 2025-04-04T04:25:48.620190+00:00 | 2025-04-04T04:25:48.620190+00:00 | 1 | false | # Code
```java []
class Solution {
public boolean isPossibleToSplit(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums)
map.put(num, map.getOrDefault(num, 0) + 1);
for (Map.Entry<Integer, Integer> entry : map.entrySet())
if (entry.getValue() > 2)
return false;
return true;
}
}
``` | 0 | 0 | ['Hash Table', 'Counting', 'Java'] | 0 |
split-the-array | Java | Cakewalk Solution 🍰 | 100% Faster | java-cakewalk-solution-100-faster-by-tej-vl7h | IntuitionWe need to split the given array nums into two equal halves, nums1 and nums2, while ensuring that both contain distinct elements.To do this, no element | teja_1403 | NORMAL | 2025-04-01T05:05:03.665669+00:00 | 2025-04-01T05:05:03.665669+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We need to split the given array nums into two equal halves, nums1 and nums2, while ensuring that both contain distinct elements.
To do this, no element in nums should appear more than twice. If any number appears more than twice, we cannot form two sets where all elements are distinct.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Using a Frequency Array:
- Since the given numbers are constrained between [1, 100], we can use a frequency array arr[101] instead of a HashMap to avoid O(n) space complexity.
- Iterate through nums and update the frequency count in arr[num].
- If any number appears more than twice (arr[num] > 2), return false immediately.
- If all numbers appear at most twice, return true.
# Complexity
- Time complexity: O(n) for single pass.
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1) for creating arr[101].
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean isPossibleToSplit(int[] nums) {
// HashMap<Integer,Integer> map = new HashMap<>();
// for(int num : nums){
// map.put(num,map.getOrDefault(num,0)+1);
// }
// for(int k : map.keySet()){
// if(map.get(k)>2){
// return false;
// }
// }
// return true;
// O(n),O(1)
// Store count of digits [1-100] according to constraints
// as index 0 and missing elements in array
// will be by default 0
int[] arr = new int[101];
for(int num : nums){
arr[num]++;
// Condition: if count>2 which means splitted array
// won't have distinct elements
if(arr[num]>2){
return false;
}
}
return true;
}
}
``` | 0 | 0 | ['Array', 'Math', 'Java'] | 0 |
split-the-array | TP | tp-by-sangram1989-a9go | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Sangram1989 | NORMAL | 2025-03-31T18:36:35.718383+00:00 | 2025-03-31T18:36:35.718383+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean isPossibleToSplit(int[] nums) {
HashMap<Integer, Integer> freq = new HashMap<>();
int i = 0;
if (nums.length % 2 != 0)
return false;
while (i < nums.length) {
if (!freq.containsKey(nums[i])){
freq.put(nums[i],1);
} else if (freq.containsKey(nums[i])) {
Integer val= freq.get(nums[i]);
freq.put(nums[i],val+1);
}
if (freq.get(nums[i])>2) {
return false;
}
i++;
}
return true;
}
}
``` | 0 | 0 | ['Java'] | 0 |
split-the-array | Simple Swift Solution | simple-swift-solution-by-felisviridis-ympr | CodeCode | Felisviridis | NORMAL | 2025-03-31T08:33:56.857369+00:00 | 2025-03-31T08:38:12.534630+00:00 | 2 | false | 
# Code
```swift []
class Solution {
func isPossibleToSplit(_ nums: [Int]) -> Bool {
var freq = [Int: Int]()
for num in nums {
freq[num, default: 0] += 1
}
for (_, value) in freq {
if value > 2 {
return false
}
}
return true
}
}
```

# Code
```swift []
class Solution {
func isPossibleToSplit(_ nums: [Int]) -> Bool {
var freq = [Int: Int]()
for num in nums {
freq[num, default: 0] += 1
if freq[num]! > 2 {
return false
}
}
return true
}
}
``` | 0 | 0 | ['Swift'] | 0 |
split-the-array | isPossibleToSplit c++ | ispossibletosplit-c-by-glider4d-evr9 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | glider4d | NORMAL | 2025-03-24T22:52:23.205796+00:00 | 2025-03-24T22:52:23.205796+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool isPossibleToSplit(vector<int>& nums) {
std::unordered_map<int, int> buf;
for (auto n : nums) {
if (buf[n] == 2)
return false;
buf[n]++;
}
return true;
}
};
``` | 0 | 0 | ['C++'] | 0 |
split-the-array | EASY PYTHON CODE | easy-python-code-by-vishnuande2006-xr8z | Code | vishnuande2006 | NORMAL | 2025-03-24T15:44:14.049374+00:00 | 2025-03-24T15:44:14.049374+00:00 | 2 | false |
# Code
```python3 []
class Solution:
def isPossibleToSplit(self, nums: List[int]) -> bool:
nums.sort()
n1 = []
n2 = []
for i in range(0,len(nums),2):
n1.append(nums[i])
n2.append(nums[i+1])
if len(set(n1)) == len(set(n2)) == (len(nums)//2):
return True
return False
``` | 0 | 0 | ['Python3'] | 0 |
split-the-array | split the array easy solution for beginner beats[45%] | split-the-array-easy-solution-for-beginn-c6ya | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Abhishek-web | NORMAL | 2025-03-24T14:20:11.602007+00:00 | 2025-03-24T14:20:11.602007+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool isPossibleToSplit(vector<int>& nums) {
unordered_map<int,int>count;
for(auto n:nums){
count[n]++;
if(count[n]>2){
return false;
}
}
return true;
}
};
``` | 0 | 0 | ['C++'] | 0 |
split-the-array | Easy Solution with frequency approach | easy-solution-with-frequency-approach-by-uo4o | IntuitionHere our intution is to make distinct numbers in each array the count in each array should not be >1 i.e count in original array should not be >2.Appr | Kartisan | NORMAL | 2025-03-20T09:31:25.075538+00:00 | 2025-03-20T09:31:25.075538+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Here our intution is to make distinct numbers in each array the count in each array should not be >1 i.e count in original array should not be >2.
# Approach
<!-- Describe your approach to solving the problem. -->
Creating a Frequency array to count frequency of nummbers, if the freq is >2 retrun false else return true.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(n)
# Code
```java []
class Solution {
public boolean isPossibleToSplit(int[] nums) {
int n=nums.length;
// if(n%2!=0)return false;
int[] f = new int[101];
for(int k: nums){
f[k]++;
}
for(int k: f){
if(k>2)return false;
}
return true;
}
}
``` | 0 | 0 | ['Java'] | 0 |
split-the-array | easy | easy-by-mr_ramzan-ubnl | Code | mr_ramzan | NORMAL | 2025-03-17T17:14:22.777351+00:00 | 2025-03-17T17:14:22.777351+00:00 | 2 | false |
# Code
```cpp []
class Solution {
public:
bool isPossibleToSplit(vector<int>& nums) {
unordered_map<int,int> map;
for(int &n:nums) map[n]++;
for(auto &p:map){
if(p.second>2) return false;
}
return true;
}
};
``` | 0 | 0 | ['Array', 'Hash Table', 'Counting', 'C++'] | 0 |
split-the-array | Easy to understand solution in Java. Beats 93.14 % | easy-to-understand-solution-in-java-beat-t7o1 | Complexity
Time complexity:
O(n)
Space complexity:
O(n)
Code | Khamdam | NORMAL | 2025-03-14T15:57:59.566884+00:00 | 2025-03-14T15:57:59.566884+00:00 | 3 | false | # Complexity
- Time complexity:
O(n)
- Space complexity:
O(n)
# Code
```java []
class Solution {
public boolean isPossibleToSplit(int[] nums) {
int[] freq = new int[101];
for (int num : nums) {
freq[num]++;
if (freq[num] > 2) {
return false;
}
}
return true;
}
}
``` | 0 | 0 | ['Java'] | 0 |
split-the-array | Solution which is done in 100 beats | solution-which-is-done-in-100-beats-by-p-4370 | IntuitionApproachComplexity
Time complexity:
O(n)
Space complexity:
O(n)
Code | Pedapudi_Akhila | NORMAL | 2025-03-13T10:44:51.149456+00:00 | 2025-03-13T10:44:51.149456+00:00 | 5 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
O(n)
- Space complexity:
O(n)
# Code
```cpp []
class Solution {
public:
bool isPossibleToSplit(vector<int>& nums)
{
int n=nums.size();
unordered_map<int,int>freq;
for(int num: nums)
{
freq[num]++;
if(freq[num]>2)
{
return false;
}
}
return true;
}
};
``` | 0 | 0 | ['C++'] | 0 |
split-the-array | Solution in java | solution-in-java-by-suraj_khatri11-9o61 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | suraj_khatri11 | NORMAL | 2025-03-11T10:09:32.223194+00:00 | 2025-03-11T10:09:32.223194+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean isPossibleToSplit(int[] nums) {
HashMap<Integer,Integer> hm = new HashMap<>();
for(int i = 0; i < nums.length; i++){
hm.put(nums[i],hm.getOrDefault(nums[i] , 0 ) + 1);
}
for(Integer key : hm.keySet()){
if(hm.get(key) > 2){
return false;
}
}
return true;
}
}
``` | 0 | 0 | ['Java'] | 0 |
split-the-array | C++ beginners friendly solution | c-beginners-friendly-solution-by-neharaj-rcuz | IntuitionApproachfirst sort the array
just comparing the occurence of elemnts if it is 3 times than it should return falseComplexity
Time complexity:
Space com | NehaRajpoot | NORMAL | 2025-03-09T06:23:16.663128+00:00 | 2025-03-09T06:23:16.663128+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
first sort the array
just comparing the occurence of elemnts if it is 3 times than it should return false
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool isPossibleToSplit(vector<int>& nums) {
int n=nums.size();
sort(nums.begin(),nums.end());
for(int i=0;i<n-2;i++){
if(nums[i]==nums[i+1] && nums[i]==nums[i+2]) return false;
}
return true;
}
};
``` | 0 | 0 | ['C++'] | 0 |
split-the-array | best approach | best-approach-by-prince_singh_008-y1t8 | IntuitionApproachComplexity
Time complexity:
o(n)
Space complexity:
Code | prince_singh_007_ | NORMAL | 2025-03-05T19:31:36.636204+00:00 | 2025-03-05T19:31:36.636204+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
o(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool isPossibleToSplit(vector<int>& nums) {
int data[1000]={0};
int n=nums.size();
for(int i=0;i<n;i++){
data[nums[i]]++;
if(data[nums[i]]>2){
return false;
}
}
return true;
}
};
``` | 0 | 0 | ['C++'] | 0 |
split-the-array | Using Hash map | using-hash-map-by-ritam05-yuwa | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Ritam_Majumdar | NORMAL | 2025-03-04T07:52:03.951963+00:00 | 2025-03-04T07:52:03.951963+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool isPossibleToSplit(vector<int>& nums) {
unordered_map<int,int>count;
int maxf=0;
for(int i=0;i<nums.size();i++){
count[nums[i]]++;
maxf=max(maxf,count[nums[i]]);
}
if(maxf>2){
return false;
}else{
return true;
}
}
};
``` | 0 | 0 | ['C++'] | 0 |
split-the-array | 🐍fastest solution💥🔥✅ | fastest-solution-by-juantorrenegra-7bhr | Intuitionif a number is repeated more than 2 times return FalseApproachdo a for loop checking if any nums.count is higher than 2Complexity
Time complexity:
O(n | juantorrenegra | NORMAL | 2025-02-27T17:55:30.933312+00:00 | 2025-02-27T17:55:30.933312+00:00 | 3 | false | # Intuition
if a number is repeated more than 2 times return False
# Approach
do a for loop checking if any nums.count is higher than 2
# Complexity
- Time complexity:
O(n2)
- Space complexity:
O(1)
# Code
```python []
class Solution(object):
def isPossibleToSplit(self, nums):
for i in nums:
if nums.count(i)>2:
return False
return True
``` | 0 | 0 | ['Python'] | 0 |
split-the-array | Pyhton 3 - Beats 100% | pyhton-3-beats-100-by-zacharylupstein-ni4t | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | zacharylupstein | NORMAL | 2025-02-27T02:23:26.471394+00:00 | 2025-02-27T02:23:26.471394+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def isPossibleToSplit(self, nums: List[int]) -> bool:
map = {}
for i in range(0,len(nums)):
if nums[i] in map:
current = map[nums[i]]
if current == 2:
return False
map[nums[i]] = current + 1
else:
map[nums[i]] = 1
return True
``` | 0 | 0 | ['Python3'] | 0 |
split-the-array | hash map | hash-map-by-qahramon1111-igh4 | Intuitionso instead of sitting down and thinking about how do i solve this problem i used the hashmap data sructure.ApproachEasy approach is that u get the elem | jamesromanov | NORMAL | 2025-02-24T13:10:43.178062+00:00 | 2025-02-24T13:10:43.178062+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
so instead of sitting down and thinking about how do i solve this problem i used the hashmap data sructure.
# Approach
<!-- Describe your approach to solving the problem. -->
Easy approach is that u get the elements and occurences of them and save it to one object. while adding them i checked if the one elements occurences greater than two then return false. WHY? beauce if one number has occurences of 3 it cannot be unique when we split the array.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(1) i guess
# Code
```javascript []
/**
* @param {number[]} nums
* @return {boolean}
*/
var isPossibleToSplit = function(nums) {
let obj = {}
for(let i in nums ){
if(obj[nums[i]]){
obj[nums[i]] += 1;
} else {
obj[nums[i]] = 1;
}
if(obj[nums[i]] > 2){
return false
}
}
return true;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
split-the-array | Python (Simple Hashmap) | python-simple-hashmap-by-nk_nidhi-sae6 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | NK_nidhi | NORMAL | 2025-02-21T15:20:42.676230+00:00 | 2025-02-21T15:20:42.676230+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def isPossibleToSplit(self, nums: List[int]) -> bool:
d, n = {}, len(nums)
for i in nums:
if i in d:
d[i] += 1
else:
d[i] = 1
for k in d:
if d[k] > 2:
return False
return True
``` | 0 | 0 | ['Python3'] | 0 |
split-the-array | Easy Solution 🚀 || C++ || Beats 100% || TC - O(n) | easy-solution-c-beats-100-tc-on-by-nitin-nkhw | Complexity
Time complexity: O(n)
Space complexity: O(n)
Code | nitinkumar-19 | NORMAL | 2025-02-20T17:08:19.489771+00:00 | 2025-02-20T17:08:19.489771+00:00 | 4 | false | # Complexity
- Time complexity: O(n)
- Space complexity: O(n)
# Code
```cpp []
class Solution {
public:
bool isPossibleToSplit(vector<int>& nums) {
unordered_map<int, int> mp;
for(int i=0;i<nums.size();i++){
mp[nums[i]]++;
if(mp[nums[i]]>2) return false;
}
return true;
}
};
``` | 0 | 0 | ['C++'] | 0 |
split-the-array | Optimized simple solution - beats 93.51%🔥 | optimized-simple-solution-beats-9351-by-pioqx | Complexity
Time complexity: O(N)
Space complexity: O(1)
Code | cyrusjetson | NORMAL | 2025-02-17T07:02:54.956804+00:00 | 2025-02-17T07:02:54.956804+00:00 | 4 | false | # Complexity
- Time complexity: O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean isPossibleToSplit(int[] nums) {
int[] t = new int[101];
for (int i : nums) {
t[i]++;
if (t[i] > 2) return false;
}
return true;
}
}
``` | 0 | 0 | ['Java'] | 0 |
split-the-array | SPLIT THE ARRAY. | split-the-array-by-itz_shrivastava_ji-bn7t | IntuitionAS IT WWAS CLEAR FROM THE QUESTION THAT ELEMENTS SHOULD BE DISTINCT , SO THE COUNT OF THE ELEMENT CANT EXCEED 2 RIGHT , AND THE LENGTH OF THE ARRAY SHO | itz_Shrivastava_Ji | NORMAL | 2025-02-14T04:07:20.889691+00:00 | 2025-02-14T04:07:20.889691+00:00 | 4 | false | # Intuition
AS IT WWAS CLEAR FROM THE QUESTION THAT ELEMENTS SHOULD BE DISTINCT , SO THE COUNT OF THE ELEMENT CANT EXCEED 2 RIGHT , AND THE LENGTH OF THE ARRAY SHOULD BE EVEN ALSO .
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
- O(2n),
- O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
- O(n), used the hash map.
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool isPossibleToSplit(vector<int>& nums) {
// you have to check the count of every number and if count of each each is <=2; and total numbers total count sum
int n=nums.size();
map<int,int> mpp;
if(n%2==0){
for(int i:nums){
mpp[i]++;
}
}
bool flag=false;
for(auto it:mpp){
if(it.second<=2){
flag=true;
}
else{
return false;
}
}
return flag;
}
};
``` | 0 | 0 | ['Array', 'Hash Table', 'C++'] | 0 |
split-the-array | if(looking for easy solution){1ms , 99% beats solution is here for you}else{continue;} | iflooking-for-easy-solution1ms-99-beats-gstzn | follow me on instagram : @ku_.k_kuApproachComplexity
Time complexity:
Space complexity:
Code | mernstack | NORMAL | 2025-02-12T13:16:27.419900+00:00 | 2025-02-12T13:16:27.419900+00:00 | 1 | false | follow me on instagram : @ku_.k_ku
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums
* @return {boolean}
*/
var isPossibleToSplit = function(nums) {
nums.sort((a,b)=>a-b)
for(let i=0;i<nums.length;i++){
if((nums.lastIndexOf(nums[i])-i)>=2){
return false
}
}
return true
};
``` | 0 | 0 | ['JavaScript'] | 0 |
split-the-array | Easy solution | easy-solution-by-gandhip1361-vxcy | IntuitionApproachComplexity
Time complexity:
O(n)
Space complexity:
O(n)
Code | gandhip1361 | NORMAL | 2025-02-11T13:52:14.449750+00:00 | 2025-02-11T13:52:14.449750+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
O(n)
- Space complexity:
O(n)
# Code
```java []
class Solution {
public boolean isPossibleToSplit(int[] nums) {
if (nums.length % 2 != 0) {
return false;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
map.put(nums[i], map.get(nums[i]) + 1);
//Only 2 duplicates needed to get 2 arrays with distinct elements
if (map.get(nums[i]) > 2) {
return false;
}
} else {
map.put(nums[i], 1);
}
}
return true;
}
}
``` | 0 | 0 | ['Hash Table', 'Java'] | 0 |
number-complement | 3-line / 1-line C++ | 3-line-1-line-c-by-lzl124631x-7n5q | See my latest update in repo LeetCode\n\n## Solution 1.\n\n\n// OJ: https://leetcode.com/problems/number-complement/\n// Author: github.com/lzl124631x\n// Time: | lzl124631x | NORMAL | 2017-01-08T09:13:16.218000+00:00 | 2022-01-04T08:00:08.950121+00:00 | 56,275 | false | See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1.\n\n```\n// OJ: https://leetcode.com/problems/number-complement/\n// Author: github.com/lzl124631x\n// Time: O(1) as there are at most 32 bits to move\n// Space: O(1)\nclass Solution {\npublic:\n int findComplement(int num) {\n unsigned mask = ~0;\n while (num & mask) mask <<= 1;\n return ~mask & ~num;\n }\n};\n```\n\nFor example,\n```\nnum = 00000101\nmask = 11111000\n~mask & ~num = 00000010\n```\n\n## Solution 2. \n\n```cpp\n// OJ: https://leetcode.com/problems/number-complement/\n// Author: github.com/lzl124631x\n// Time: O(1)\n// Space: O(1)\nclass Solution {\npublic:\n int findComplement(int n) {\n return (unsigned)~0 >> __builtin_clz(n) ^ n;\n }\n};\n```\n\nFor example:\n\n```\nn = 00000101\n(unsigned)~0 >> __builtin_clz(n) = 00000111\n(unsigned)~0 >> __builtin_clz(n) ^ n = 00000010\n```\n | 290 | 3 | [] | 46 |
number-complement | Java, very simple code and self-evident, explanation | java-very-simple-code-and-self-evident-e-0gba | for example:\n100110, its complement is 011001, the sum is 111111. So we only need get the min number large or equal to num, then do substraction\n\n public | dongdl | NORMAL | 2017-01-16T06:07:42.142000+00:00 | 2018-10-01T21:27:07.933367+00:00 | 32,526 | false | for example:\n100110, its complement is 011001, the sum is 111111. So we only need get the min number large or equal to num, then do substraction\n```\n public int findComplement(int num) \n {\n int i = 0;\n int j = 0;\n \n while (i < num)\n {\n i += Math.pow(2, j);\n j++;\n }\n \n return i - num;\n }\n``` | 238 | 1 | [] | 30 |
number-complement | ✅100.0%🔥Easy Solution🔥With Explanation🔥 | 1000easy-solutionwith-explanation-by-mra-i4uk | Intuition\n#### When asked to find the complement of an integer, the idea is to flip every bit in its binary representation\u2014changing 0s to 1s and 1s to 0s. | MrAke | NORMAL | 2024-08-22T01:10:06.304091+00:00 | 2024-08-22T01:10:06.304113+00:00 | 42,710 | false | # Intuition\n#### When asked to find the complement of an integer, the idea is to flip every bit in its binary representation\u2014changing `0`s to `1`s and `1`s to `0`s. For example, the complement of 5 (which is `101` in binary) is `010`, which is `2` in decimal.\n---\n\n# Approach\n#### `Determine the Binary Length`: First, calculate the bit length of the integer. This is the number of bits required to represent the number in binary.\n#### `Create a Mask`: Generate a binary number (mask) that has all bits set to 1 for the same length as the number\'s binary representation. This mask helps in flipping all bits when XORed with the original number.\n#### `Flip the Bits`: Perform the XOR operation between the number and the mask. XORing with 1 flips the bit (0 becomes 1 and 1 becomes 0).\n#### `Return the Result`: The result of the XOR operation is the complement of the original number.\n---\n\n\n\n\n- # Time complexity:\n##### The time complexity is $$O(1)$$. The operations (finding bit length, shifting bits, XOR operation) are all constant time operations regardless of the size of the integer.\n- # Space complexity:\n##### The space complexity is $$O(1)$$. We are using a constant amount of extra space (only a few variables) that does not scale with the input size.\n---\n# Code\n```python []\nclass Solution:\n def findComplement(self, num: int) -> int:\n bit_length = num.bit_length()\n \n mask = (1 << bit_length) - 1\n \n return num ^ mask\n```\n```C++ []\nclass Solution {\npublic:\n int findComplement(int num) {\n if (num == 0) return 1;\n \n unsigned int mask = ~0;\n \n while (num & mask) {\n mask <<= 1;\n }\n \n return ~mask & ~num;\n }\n};\n\n```\n```javascript []\nvar findComplement = function(num) {\n if (num === 0) return 1;\n\n const bitLength = num.toString(2).length;\n \n const mask = (1 << bitLength) - 1;\n \n return num ^ mask;\n};\n\n```\n```java []\nclass Solution {\n public int findComplement(int num) {\n if (num == 0) return 1;\n\n int bitLength = Integer.toBinaryString(num).length();\n \n int mask = (1 << bitLength) - 1;\n \n return num ^ mask;\n }\n}\n\n```\n```C# []\npublic class Solution {\n public int FindComplement(int num) {\n int bitLength = (int)Math.Log(num, 2) + 1;\n \n int mask = (1 << bitLength) - 1;\n \n return num ^ mask;\n }\n}\n\n```\n---\n\n\n\n | 185 | 2 | ['Bit Manipulation', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#'] | 17 |
number-complement | Simple Python | simple-python-by-ipeq1-hcy8 | \nclass Solution(object):\n def findComplement(self, num):\n i = 1\n while i <= num:\n i = i << 1\n return (i - 1) ^ num\n\n\ | ipeq1 | NORMAL | 2017-01-08T07:30:34.390000+00:00 | 2022-07-11T20:09:43.942562+00:00 | 27,972 | false | ```\nclass Solution(object):\n def findComplement(self, num):\n i = 1\n while i <= num:\n i = i << 1\n return (i - 1) ^ num\n```\n\nFYI: pomodoro timer helps to obtain higher time ROI: [e-tomato.online](http://e-tomato.online) | 152 | 1 | [] | 27 |
number-complement | Java 1 line bit manipulation solution | java-1-line-bit-manipulation-solution-by-b7vs | I post solution first and then give out explanation. Please think why does it work before read my explanation.\n\n\npublic class Solution {\n public int find | shawngao | NORMAL | 2017-01-08T13:52:23.355000+00:00 | 2018-10-03T13:32:39.294822+00:00 | 52,527 | false | I post solution first and then give out explanation. Please think why does it work before read my explanation.\n\n```\npublic class Solution {\n public int findComplement(int num) {\n return ~num & ((Integer.highestOneBit(num) << 1) - 1);\n }\n}\n```\n\nAccording to the problem, the result is\n1. The ```flipped``` version of the original ```input``` but\n2. Only flip ```N``` bits within the range from ```LEFTMOST``` bit of ```1``` to ```RIGHTMOST```. \nFor example input = ```5``` (the binary representation is ```101```), the ```LEFTMOST``` bit of ```1``` is the third one from ```RIGHTMOST``` (```100```, ```N``` = 3). Then we need to flip 3 bits from ```RIGHTMOST``` and the answer is ```010```\n\nTo achieve above algorithm, we need to do 3 steps:\n1. Create a bit mask which has ```N``` bits of ```1``` from ```RIGHTMOST```. In above example, the mask is ```111```. And we can use the decent Java built-in function ```Integer.highestOneBit``` to get the ```LEFTMOST``` bit of ```1```, left shift one, and then minus one. Please remember this wonderful trick to create bit masks with ```N``` ones at ```RIGHTMOST```, you will be able to use it later.\n2. Negate the whole input number.\n3. ```Bit AND``` numbers in step ```1``` and ```2```.\n\nThree line solution if you think one line solution is too confusing:\n```\npublic class Solution {\n public int findComplement(int num) {\n int mask = (Integer.highestOneBit(num) << 1) - 1;\n num = ~num;\n return num & mask;\n }\n}\n```\n\n```UPDATE```\nAs several people pointed out, we don't need to left shift 1. That's true because the highest ```1``` bit will always become ```0``` in the ```Complement``` result. So we don't need to take care of that bit.\n\n```\npublic class Solution {\n public int findComplement(int num) {\n return ~num & (Integer.highestOneBit(num) - 1);\n }\n}\n``` | 135 | 0 | [] | 31 |
number-complement | C++ EASY TO SOLVE || Different Variations of code with detailed exaplanations | c-easy-to-solve-different-variations-of-af9vu | Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.\n\nIntuition:-\nThere is not m | Cosmic_Phantom | NORMAL | 2021-12-27T03:15:41.395534+00:00 | 2024-08-23T02:30:11.539435+00:00 | 11,162 | false | Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.\n\n**Intuition:-**\nThere is not much of a intuition in this question as the question is loud and clear about it\'s use of bit manipulation .\n\nTo make things a bit more interesting let\'s do this question with and wihout bit manipulation\n\n* **Using Bit Manipulations:---**\n\n**Bit masking can be summarized with this image (^_^)**\n \nThus, we can conclude that masking means to keep/change/remove a desired part of information.\n\n**Dry run of bitmasking:-**\n\n\n**Code1[Using bitmasking]:-**\n```\nclass Solution {\npublic:\n int findComplement(int num) {\n unsigned mask = ~0;\n while( mask & num ) mask = mask << 1;\n return ~num ^ mask;\n }\n};\n```\n**Time Complexity:** *`O(log(num)) = O(since we will be moving at most 32bits only) = O(1)`*\n**Space Complexity:** *`O(1)`*\n\n**Code2[Using xor]:-**\nBasic idea is to find the smallest power of 2 that is larger than the `input number num`, and output the difference between `powerof2s` and `num` . \n\n**Dry run:-**\n```\nFor example let\'s the example from description of the question:-\nInput: num = 5(101) ,\nThus the smallest power of 2 (and larger than 5) is 8 (1000)\nThe output should be 8 - 5 - 1 = 2 (010).\n```\n\n```\nclass Solution {\npublic:\n int findComplement(int num) {\n long powerof2s = 2, temp = num;\n \n while(temp>>1) {\n temp >>= 1;\n powerof2s <<= 1;\n }\n \n return powerof2s - num - 1;\n }\n};\n```\n.\n\n* **Without using Bit manipulation:-**\n\n***Code:-***\n```\nclass Solution {\npublic:\n int findComplement(int num) {\n vector<int> temp; \n\t\t// convert to binary representation\n while( num != 0 ){\n temp.push_back( num % 2 );\n num /= 2;\n } \n\t\t// make complement\n for(int i=0; i<temp.size(); i++){\n if( temp[i] == 1 ) temp[i] = 0;\n else if( temp[i] == 0 ) temp[i] = 1;\n } int res = 0;\n for(int i=temp.size()-1; i>-1; i--) res = res * 2 + temp[i];\n return res;\n }\n};\n```\n\n | 122 | 14 | ['Bit Manipulation', 'C', 'C++'] | 9 |
number-complement | maybe fewest operations | maybe-fewest-operations-by-stefanpochman-dsaj | Spread the highest 1-bit onto all the lower bits. Then xor with that.\n\nint findComplement(int num) {\n int mask = num;\n mask |= mask >> 1;\n mask |= | stefanpochmann | NORMAL | 2017-01-10T16:15:52.171000+00:00 | 2018-10-19T13:13:24.644131+00:00 | 16,282 | false | Spread the highest 1-bit onto all the lower bits. Then xor with that.\n```\nint findComplement(int num) {\n int mask = num;\n mask |= mask >> 1;\n mask |= mask >> 2;\n mask |= mask >> 4;\n mask |= mask >> 8;\n mask |= mask >> 16;\n return num ^ mask;\n}\n``` | 110 | 3 | [] | 12 |
number-complement | Python 4 ways | python-4-ways-by-flag_to-lg8h | Flip bit by bit.\n\nclass Solution(object):\n def findComplement(self, num):\n i = 1\n while num >= i:\n num ^= i\n i <<= | flag_to | NORMAL | 2017-01-10T21:35:42.028000+00:00 | 2018-09-21T16:04:22.966292+00:00 | 7,621 | false | 1. Flip bit by bit.\n```\nclass Solution(object):\n def findComplement(self, num):\n i = 1\n while num >= i:\n num ^= i\n i <<= 1\n return num\n```\n2. Find the bit length (say L) and flip num by **num ^ 11...1** (L ones).\n```\n def findComplement(self, num):\n return num ^ ((1<<num.bit_length())-1)\n```\n3. Again find the bit length first.\n```\n def findComplement(self, num):\n return num ^ ((1 << len(bin(num)) - 2) - 1)\n```\n4.\n```\ndef findComplement(self, num):\n return num ^ ((2<<int(math.log(num, 2)))-1)\n```\nWe can also flip num first (including the leading zeros) using ```~num``` and then get the last L bits by ```& 11...1``` (L ones).\n\nFor example,\n```\n def findComplement(self, num):\n return ~num & ((1<<num.bit_length())-1)\n``` | 65 | 1 | [] | 9 |
number-complement | ✅ [C++/Python] Simple Solutions w/ Explanation | Brute-Force +Bit-Manipulation Tricks + In-Built | cpython-simple-solutions-w-explanation-b-t3vb | We are given an integer num and we need to return its complement\n\n---\n\n\u2714\uFE0F Solution - I (Brute-Force)\n\nWe can simply iterate and find the leftmos | archit91 | NORMAL | 2021-12-27T07:47:23.888883+00:00 | 2021-12-27T09:04:20.143868+00:00 | 3,411 | false | We are given an integer `num` and we need to return its complement\n\n---\n\n\u2714\uFE0F ***Solution - I (Brute-Force)***\n\nWe can simply iterate and find the leftmost bit (MSB) that is set. From that point onwards, we flip every bit till we reach the rightmost bit (LSB). To flip a bit, we can use `^ 1` (XOR 1) operation. This will flip a bit to 0 if it is set and flip to 1 if it is unset.\n\n**C++**\n```cpp\nclass Solution {\npublic:\n int findComplement(int num) {\n int i = 31;\n while((num & 1 << i) == 0) i--; // skip the left 0 bits till we reach the 1st set bit from left\n while(i >= 0)\n num ^= 1 << i--; // flip all bits by XORing with 1\n return num;\n }\n};\n```\n\n**Python**\n```python\nclass Solution:\n def findComplement(self, num):\n i = 31\n while (num & 1 << i) == 0: \n i -= 1\n while i >= 0:\n num ^= 1 << i\n i -= 1\n return num\n```\n\n***Time Complexity :*** <code>O(N)</code>, where `N` is the number of bits. In this case, since we are starting from `i=31`, it should be constant but I am denoting time complexity of this approach as generalized `O(N)`\n***Space Complexity :*** `O(1)`\n\n---\n\n\u2714\uFE0F ***Solution - II (Bit-Manipulation Tricks)***\n\nThe above method basically finds the leftmost set bit and XORs the remaining bits with 1. A more efficient way to do the same would be to simply XOR `num` with another number having all bits to the right of nums\'s 1st set bit as 1 and rest bit to left as 0. This would achieve the same thing as above.\n\n```py\nFor eg. num = 13\n=> num = 13 (1101)\n=> mask = 15 (1111)\n--------------------\n ^ 2 (0010) We got all the bits flipped\n```\n\n* **But how to get `mask`?** \n\t* A simple way would be to initialize `mask = 0` and keep flipping bits of it to 1 starting from the rightmost bit (LSB) till we reach the leftmost set bit of `num`. \n\n* **Now, how do we know that we reached the leftmost set bit in `num`?**\n\t* We use another variable `tmp = num`. Each time, we will rightshift tmp essentially removing the rightmost bit. When we remove the leftmost set bit from it, it will become 0. Thus, we loop till `tmp` is not 0.\n\n**C++**\n```cpp\nclass Solution {\npublic:\n int findComplement(int num) {\n int mask = 0; // all bits in mask are initially 0\n for(int tmp = num; tmp; tmp >>= 1) // set bits in mask to 1 till we reach leftmost set bit in num\n mask = (mask << 1) | 1; // leftshifts and sets the rightmost bit to 1\n\t\t\t\n return mask ^ num; // finally XORing with mask will flip all bits in num\n }\n};\n```\n\n**Python**\n```python\nclass Solution:\n def findComplement(self, num):\n mask, tmp = 0, num\n while tmp:\n mask = (mask << 1) | 1\n tmp >>= 1\n return mask ^ num\n```\n\t\nAnother way to do the same would be to the other way around and start with mask with all bits as 1. Then we keep setting rightmost bits in `mask` to 0 one by one till there are no common set bits left in `num` and `mask` (`num & mask == 0` when no common set bits are present).\n\n```py\nFor eg. num = 13 (1101) and mask = -1 (111...1111) [all 32 set bits are set in -1 binary representation]\n \n1. num = 000...1101 \n mask = 111...1110 => we still have common set bits\n \n2. num = 000...1101 \n mask = 111...1100 => we still have common set bits \n \n3. num = 000...1101\n mask = 111...1000 => we still have common set bits \n \n4. num = 000...1101 \n mask = 111...0000 => no more common bits left\n```\n\n* **Now what?**\n\n\t* Now we can simply flip all bits in `mask` (using `~` operator). It will now have all rightmost bits set to one starting from leftmost set bit in `num`, i.e, we now have the same `mask` that we had in previous approach.\n\t* Now, we can XOR it with `num` and we get the flipped result\n\n**C++**\n```cpp\nclass Solution {\npublic:\n int findComplement(int num) {\n uint mask = -1; // -1 is represented in binary as all bits set to 1\n while(mask & num) mask <<= 1; // remove rightmost bits 1 by 1 till no common bits are left\n return ~mask ^ num; // XORs with 1 & flips all bits in num starting from the leftmost set bit \n }\n};\n```\n\n**Python**\n```python\nclass Solution:\n def findComplement(self, num):\n mask = -1\n while mask & num: mask <<= 1\n return ~mask ^ num\n```\n\nThis approach used 1 less operation inside loop (1st approach used 3 operations: right-shift `>>` on tmp, left-shift `<<` on mask and `|` with 1 to set rightmost bit. This one uses 2: `&` to check if there are common bits in `mask` and `num` and left-shift `<<` to remove the right set bits one by one)\n\n***Time Complexity :*** <code>O(P) / O(log num)</code>, where `P` is the position of leftmost set bit in `num`. <code>O(P) ~ O(log<sub>2</sub>(num))</code>\n***Space Complexity :*** `O(1)`\n\n---\n\n\u2714\uFE0F ***Solution - III (Flip Bits from Right to Left)***\n\nWe can start from the right-end and flip bits one by one. This is somewhat similar to 1st solution in above appraoch. But here we will not use mask but rather a bit starting with `i=1` and just directly XOR it with `num`, then left-shift it & repeat thus flipping the bits in `num` one by one. \n\nSo, how do we know when to stop? We stop as soon `i > num`. This denotes that we have passed the leftmost set bit in `num` and thus we have flipped all the bits that needed to be flipped.\n\n**C++**\n```cpp\nclass Solution {\npublic:\n int findComplement(int num) {\n int i = 1;\n while(i <= num)\n num ^= i,\n i <<= 1;\n return num;\n }\n};\n```\n\n**Python**\n```python\nclass Solution():\n def findComplement(self, num):\n i = 1\n while i <= num:\n num ^= i\n i <<= 1\n return num \n```\n\n***Time Complexity :*** <code>O(P) / O(log num)</code>\n***Space Complexity :*** `O(1)`\n\n---\n\n\u2714\uFE0F ***Solution - IV (Built-in Methods)***\n\nThere are built-in methods provided by languages such as `__builtin_clz` in C++ which counts leading zeros, `highestOneBit` in Java which returns the number with only its leftmost bit set and so on... These methods can be used to solve this problem as well using the same logic as above.\n\n**C++**\n```cpp\nclass Solution {\npublic:\n int findComplement(int num) {\n return ~(-1u << (32 - __builtin_clz(num))) ^ num;\n// or: return ~(-1u << int(log2(num))+1) ^ num; \n }\n};\n```\n\n**Python**\n```python\nclass Solution():\n def findComplement(self, num):\n return ~(-1 << int(log2(num))+1) ^ num\n```\n\n\n***Time Complexity :*** <code>O(1)</code>, `__builtin_clz` usually translates to single machine instruction and should be considered constant. The `log` complexity might be implementation dependent but should atleast be costlier by some factor than `__builtin_clz`\n***Space Complexity :*** `O(1)`\n\n---\n---\n\n\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, comment below \uD83D\uDC47 \n\n---\n--- | 58 | 0 | [] | 6 |
number-complement | 3 line pure C | 3-line-pure-c-by-osamurai-4wpz | \nint findComplement(long num) {\n long i;\n for(i=1;i<=num;i*=2) num^=i; \n return num;\n}\n\nI basically check every bit of number by XOR'ing it with | osamurai | NORMAL | 2017-02-03T02:46:22.474000+00:00 | 2018-10-20T02:52:26.499737+00:00 | 4,783 | false | ```\nint findComplement(long num) {\n long i;\n for(i=1;i<=num;i*=2) num^=i; \n return num;\n}\n```\nI basically check every bit of number by XOR'ing it with appropriate power of 2 which leads to its invertion.\nFor example:\n```\nEntered: 4=>100;\n100 ^ 001 = 101;\n101 ^ 010 = 111;\n111 ^ 100 = 011;\nOut: 011=>3;\n``` | 55 | 1 | [] | 9 |
number-complement | Java | 0 ms | 1 liner | Explained | java-0-ms-1-liner-explained-by-prashant4-yurh | Idea:\n Flip all bits using negation operator (~) [read more here]\n Bitwise AND (&) with a bit mask of size n whose all bits are set, where n = number of bits | prashant404 | NORMAL | 2021-12-27T02:26:39.541164+00:00 | 2021-12-27T05:48:52.163304+00:00 | 8,003 | false | **Idea:**\n* Flip all bits using negation operator (~) [[read more here](https://www.ibm.com/docs/en/i/7.1?topic=expressions-bitwise-negation-operator)]\n* Bitwise AND (&) with a bit mask of size n whose all bits are set, where n = number of bits in `num`\n**Example:**\n```\nnum = 5\n num binary = 0...0101\n ~num binary = 1...1010\n\n* Now we\'ve flipped all the bits but it also flipped previously insignificant bits (0s), \nso to revert them back to 0s, we need to only keep the significant bits and turn off the insignificant bits\n* This can be done by using mask of 1s having size equal to number of bits in num. This mask is (1 << nBits) - 1\n* This is a standard mask in bit manipulation problems\n\n~num binary & mask = (1...1010) & (0...0111) = 0...0010 [Ans]\n```\n>**T/S:** O(1)/O(1)\n```\npublic int findComplement(int num) {\n\tvar nBits = (int) Math.floor((Math.log(num) / Math.log(2)) + 1);\n\tvar mask = (1 << nBits) - 1;\n\treturn ~num & mask;\n}\n```\n**Variation 2:** 1 liner variation of above method\n```\npublic int findComplement(int num) {\n\treturn ~num & (Integer.highestOneBit(num) - 1);\n}\n```\n***Please upvote if this helps*** | 51 | 6 | ['Java'] | 7 |
number-complement | [Python3] Easy One line Code -with Explanation | python3-easy-one-line-code-with-explanat-9f83 | Here\'s the code:\npython\nclass Solution:\n def findComplement(self, num: int) -> int:\n return num^(2**(len(bin(num)[2:]))-1)\n\nWhat does it mean?\ | xhon9 | NORMAL | 2020-05-04T08:13:10.626298+00:00 | 2020-05-04T08:40:02.765365+00:00 | 4,369 | false | Here\'s the code:\n```python\nclass Solution:\n def findComplement(self, num: int) -> int:\n return num^(2**(len(bin(num)[2:]))-1)\n```\nWhat does it mean?\nThe complement of a number is computable by "flipping" all the bits in his binary form.\nIn other words, that\'s nothing more than a **bitwise XOR with all 1**.\n\nFollowing the truth table:\n\n\n\nWe can easily notice what I said before.\n\nSo, now?\nNow the idea is to **transform in binary** form the input number, taking the number of bit necessary for his representation. That\'s done with `len(bin(num)[2:])`, [2:] cause the bin() function in Python3 add also an initial \'0b\' (ex: `bin(5) = \'0b101\'`, but `bin(5)[2:] = \'101\'`).\n\nAfter taking the len, **compute** `2**len` taking the first pow of 2 that is >= our number, and finally compute the `-1`.\nReasoning: doing `2**len` we get a number with leading 1 and all zeros, subtracting 1 we finally get the number with the same len of our input, formed by all 1.\n\nReturn the XOR of input and this number, and **win**!\n\n-That\'s my first post, feel free to ask and upvote :D | 44 | 1 | ['Python3'] | 9 |
number-complement | DETAILED EXPLANATION Java XOR Method Easy To Understand | detailed-explanation-java-xor-method-eas-jxnj | Let\'s say the input is num = 5 = 101 in binary\nOur mask needs to be 111 and then we will perform a XOR operation. The XOR operation says return TRUE (1) only | milan102 | NORMAL | 2018-08-09T05:45:49.487669+00:00 | 2018-09-04T22:36:25.732753+00:00 | 1,964 | false | Let\'s say the input is num = 5 = 101 in binary\nOur mask needs to be 111 and then we will perform a XOR operation. The XOR operation says return TRUE (1) only if one of the bits is true, else return FALSE (0). This means that when we XOR a 1 and a 1 bit, we will get 0. If we XOR a 1 and 0 bit, we will get 1. Thus effectively flipping the bits.\n\nThe way we get the mask to be 111 is to first get the DECIMAL VALUE OF THE FURTHER LEFT BIT of num, so in this case the furthest left bit of num represents 4. In binary this is 100. We do a single left shift, thus we get 1000 which is 8 in decimal. Then we subtract 1 to get 7 in decimal, or 111. This is the mask value we need to XOR to our original input num.\n\n```\npublic class Solution {\n public int findComplement(int num) {\n int mask = (Integer.highestOneBit(num) << 1) - 1;\n return num ^ mask;\n }\n}\n``` | 35 | 0 | [] | 5 |
number-complement | Javascript Solution - without converting to binary | javascript-solution-without-converting-t-t0t0 | Let\'s look to rundom binary number, for example: 10011.\nReverse of this number = 01100.\nLook, it\'s equal: 100000 - 10011 - 1.\n\nIdea: find the minimum near | nkuklina | NORMAL | 2020-05-04T18:18:38.132024+00:00 | 2020-05-04T18:20:32.814031+00:00 | 1,130 | false | Let\'s look to rundom binary number, for example: `10011`.\nReverse of this number = `01100`.\nLook, it\'s equal: `100000 - 10011 - 1`.\n\n**Idea:** find the minimum nearest number greater than `num` (power of 2)\n\n```\n/**\n * @param {number} num\n * @return {number}\n */\nvar findComplement = function(num) { \n let d = 2;\n while (d <= num) {\n d *= 2;\n } \n return d - num - 1;\n};\n```\n\nThe number of actions does not exceed 32. | 23 | 0 | ['JavaScript'] | 2 |
number-complement | One line solution C++ | one-line-solution-c-by-dastijr-25yv | \nclass Solution {\npublic:\n int findComplement(int num) {\n return (pow(2,floor(log2(num))+1)-1)-num;\n }\n};\n\n\nHere, floor(log2(num))+1 gives | dastijr | NORMAL | 2021-12-27T08:12:32.282747+00:00 | 2023-01-05T04:52:00.000829+00:00 | 2,272 | false | ```\nclass Solution {\npublic:\n int findComplement(int num) {\n return (pow(2,floor(log2(num))+1)-1)-num;\n }\n};\n```\n\nHere, **floor(log2(num))+1** gives us the number of bits in integer **num**.\nThe maximum value obtained with this number of bits is **pow(2,no of bits)-1**.\nWhen we **subtract from maximum value to the given input** will gives the complement of the given input.\n\nHope it helps:) \nHappy coding. | 22 | 0 | ['Bit Manipulation', 'C++'] | 3 |
number-complement | Explained | Easy to understand | Faster than 99.58% | Simple | Bit manipulation | Python Solution | explained-easy-to-understand-faster-than-57up | Later I found that this solution correponds to the second approach mentioned in the solution\n\nHere, in this soution, we are just making another bit variable t | mrmagician | NORMAL | 2020-04-02T17:23:03.693499+00:00 | 2020-04-02T17:23:53.135162+00:00 | 1,755 | false | ##### Later I found that this solution correponds to the second approach mentioned in the solution\n\nHere, in this soution, we are just making another bit variable to be full of 1\'s upto the length of bits in num and then simply returning the XOR of two\nnum = 5 = 101\nbit ===== 111\nAns ==== 010 = 2\n\n```\ndef findComplement(self, num: int) -> int:\n bit = 0\n todo = num\n while todo:\n bit = bit << 1\n bit = bit ^ 1\n todo = todo >> 1\n return bit ^ num\n```\n\n**I hope that you\'ve found the solution useful.**\n*In that case, please do upvote and encourage me to on my quest to document all leetcode problems\uD83D\uDE03*\nPS: Search for **mrmagician** tag in the discussion, if I have solved it, You will find it there\uD83D\uDE38 | 22 | 1 | ['Bit Manipulation', 'Python', 'Python3'] | 3 |
number-complement | clz finds bit length then xor->1 line||0ms Beats 100% | clz-finds-bit-length-then-xor-1-line0ms-n6b2y | Intuition\n Describe your first thoughts on how to solve this problem. \ncount how many bits the number num needs by using clz or countl_zero(since C++20)\nThen | anwendeng | NORMAL | 2024-08-22T00:29:53.701966+00:00 | 2024-08-22T10:02:13.017192+00:00 | 8,661 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ncount how many bits the number num needs by using clz or countl_zero(since C++20)\nThen xor with 0x7fffffff then & (1<<bitLen)-1 if bitLen<31\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Count bLen by using `bLen=(31-countl_zero((unsigned)num))` or system bultin `__builtin_clz`. They have the same effect like `int(log2(num))`.\n2. Compute the mask=(1<<bitLen)-1 if bitLen<31\n3. the answer is `(INT_MAX^num)&mask=(~num)&mask`.\n4. 1-liner C++ is given which is simpler; Python 1-liner is done in the similar way.\n5. For avoiding of overflow, take `1u` in 1-liner without if-branch\n6. For better understanding, add a solution using iterations with slight bit manipulations. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(\\max(\\log_2(n),32))$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```cpp []|| C++ 0ms beats 100%\nclass Solution {\npublic:\n int findComplement(int num) {\n int bLen=(31-__builtin_clz(num));\n int mask=(bLen==31)?INT_MAX:((1<<bLen)-1);\n return (INT_MAX^num)&mask;\n }\n};\n```\n# C++/Python 1-liner using bit_length()\nFor avoiding of overflow in C++, take `1u` in 1-liner\n```C++ []\nclass Solution {\npublic:\n static int findComplement(int num) {\n return num^((1u<<(32-countl_zero((unsigned)num)))-1);\n }\n};\n```\n```Python []\nclass Solution:\n def findComplement(self, num: int) -> int:\n return num^((1<<num.bit_length())-1)\n \n```\n# C++ loop with bit manipulation\n```\nclass Solution {\npublic:\n static int findComplement(int num) {\n if (num==1) return 0;\n int ans=0;\n for(int b=0; num; b++, num>>=1){// num/=2\n ans+=(1-(num&1))<<b;// (num%2==0?1:0)*(1<<b)\n }\n return ans;\n }\n};\n``` | 21 | 4 | ['Bit Manipulation', 'Bitmask', 'C++', 'Python3'] | 6 |
number-complement | Java Bit masking 100% faster | java-bit-masking-100-faster-by-saiyancod-pseu | \nclass Solution {\n public int findComplement(int num) {\n int c = 0, t = num;\n\t\t//First, you need to find how many bits are present in the given | saiyancoder | NORMAL | 2020-11-02T17:18:49.975120+00:00 | 2020-11-02T17:19:07.221184+00:00 | 1,638 | false | ```\nclass Solution {\n public int findComplement(int num) {\n int c = 0, t = num;\n\t\t//First, you need to find how many bits are present in the given number.\n while(t>0) {\n t = t>>1;\n c++;\n }\n\t\t//Now after that, create a mask of 1\'s about the size of num.\n\t\t//eg: if num = 5(101) then mask = 7(111) \n int mask = (1<<(c))-1;\n\t\t//now this mask can be used to flip all the bits in num using XOR.\n return num^mask;\n }\n}\n``` | 20 | 0 | ['Java'] | 1 |
number-complement | Python O( lg n ) XOR masking. [ w' explanation ] 有中文解析專欄 | python-o-lg-n-xor-masking-w-explanation-p55sz | Python O( log n ) sol. based on XOR masking. \n\n\u4E2D\u6587\u89E3\u6790\u5C08\u6B04\n\n---\n\nExample explanation\n\n---\nExample_#1\n\ninput: 5\n\n5 = 0b 101 | brianchiang_tw | NORMAL | 2020-01-23T03:47:35.110267+00:00 | 2024-08-22T15:22:16.394013+00:00 | 2,181 | false | Python O( log n ) sol. based on XOR masking. \n\n[\u4E2D\u6587\u89E3\u6790\u5C08\u6B04](https://vocus.cc/article/66c6eddefd89780001e679b8)\n\n---\n\nExample explanation\n\n---\nExample_#1\n\ninput: **5**\n\n5 = 0b **101**\n**bits length** of 5 = **3**\n**masking** = **2^3 -1** = 8 - 1 = **7** = 0b **111**\n\n5 = 0b **101**\n7 = 0b **111** ( **XOR** )\n\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\n**2** = 0b **010**\n\noutput: **2**\n\n---\nExample_#2\n\ninput: **9**\n\n9 = 0b **1001**\n**bits length** of 9 = **4**\n**masking** = **2^4 -1** = 16 - 1 = **15** = 0b **1111**\n\n09 = 0b **1001**\n15 = 0b **1111** ( **XOR** )\n\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\n**06** = 0b **0110**\n\noutput: **6**\n\n---\n**Implementation** with bit length calculation:\n```\nfrom math import floor\nfrom math import log\n\nclass Solution:\n def findComplement(self, num: int) -> int:\n \n bits_length = floor( log(num, 2) + 1)\n \n return num^( 2**bits_length - 1 )\n```\n\n---\n\n**Implementation** with python built-in method, **[.bit_length()](https://docs.python.org/3/library/stdtypes.html#int.bit_length)**,of integer:\n\n```\nclass Solution:\n def findComplement(self, num: int) -> int:\n \n bit_mask = 2**num.bit_length() -1 \n \n return ( num ^ bit_mask )\n```\n\n---\n\nRelated leetcode challenge:\n\n[Leetcode #1009 Complement of Base 10 Integer](https://leetcode.com/problems/complement-of-base-10-integer/) | 20 | 0 | ['Bit Manipulation', 'Bitmask', 'Python', 'Python3'] | 3 |
number-complement | Simple Java Code ☠️ | simple-java-code-by-abhinandannaik1717-ddqa | \n# Code\njava []\nclass Solution {\n public int findComplement(int num) {\n String str = Integer.toBinaryString(num);\n String res = "";\n | abhinandannaik1717 | NORMAL | 2024-08-22T02:27:12.532532+00:00 | 2024-08-22T02:27:12.532561+00:00 | 5,510 | false | \n# Code\n```java []\nclass Solution {\n public int findComplement(int num) {\n String str = Integer.toBinaryString(num);\n String res = "";\n for(int i=0;i<str.length();i++){\n if(str.charAt(i) == \'0\'){\n res += \'1\';\n }\n else{\n res += \'0\';\n }\n }\n return Integer.parseInt(res,2);\n }\n}\n```\n\n### Explanation\n\nThis code is a solution to find the complement of an integer. The complement is obtained by flipping all the 0\'s to 1\'s and all the 1\'s to 0\'s in the binary representation of the integer.\n\n### Step-by-Step Logic:\n\n1. **Convert Integer to Binary String**:\n ```java\n String str = Integer.toBinaryString(num);\n ```\n - The method `Integer.toBinaryString(num)` converts the integer `num` into its binary string representation. For example, if `num = 5`, `str` would be `"101"`.\n\n2. **Flip the Binary Digits**:\n ```java\n String res = "";\n for(int i=0;i<str.length();i++){\n if(str.charAt(i) == \'0\'){\n res += \'1\';\n }\n else{\n res += \'0\';\n }\n }\n ```\n - Here, the code iterates over each character in the binary string `str`.\n - For each character:\n - If the character is `\'0\'`, it appends `\'1\'` to the result string `res`.\n - If the character is `\'1\'`, it appends `\'0\'` to `res`.\n - This effectively flips all the bits of the binary string.\n\n For example, if `str = "101"`, after flipping, `res` would be `"010"`.\n\n3. **Convert the Resultant Binary String Back to Integer**:\n ```java\n return Integer.parseInt(res,2);\n ```\n - Finally, the method `Integer.parseInt(res, 2)` converts the binary string `res` back to an integer. The second argument `2` specifies that the string is in base 2 (binary).\n - For example, `"010"` is converted back to the integer `2`.\n\n### Example:\n- Suppose `num = 5`. The binary representation of `5` is `"101"`.\n- The flipped binary string becomes `"010"`, which corresponds to the integer `2`.\n- Therefore, the method returns `2` as the complement of `5`.\n\n### Complexity:\n- **Time Complexity**: The time complexity is `O(n)`, where `n` is the number of bits in the binary representation of the integer. This is because the code iterates over each bit once.\n- **Space Complexity**: The space complexity is also `O(n)` due to the storage of the binary string and its complement.\n\n\n\n | 18 | 0 | ['String', 'Java'] | 6 |
number-complement | Java one line solution without using AND (&) or XOR (^) | java-one-line-solution-without-using-and-zjvz | To find complement of num = 5 which is 101 in binary.\nFirst ~num gives ...11111010 but we only care about the rightmost 3 bits.\nThen to erase the 1s before 01 | yuxiangmusic | NORMAL | 2017-01-10T04:29:50.621000+00:00 | 2018-09-20T18:04:03.945284+00:00 | 7,649 | false | To find complement of ```num = 5``` which is ```101``` in binary.\nFirst ```~num``` gives ```...11111010``` but we only care about the rightmost 3 bits.\nThen to erase the ```1```s before ```010``` we can add ```1000```\n\n```\n public int findComplement(int num) {\n return ~num + (Integer.highestOneBit(num) << 1);\n }\n``` | 18 | 0 | [] | 4 |
number-complement | Beats 100% || O(32) Time O(1) Space || Easy Explanation + Code | beats-100-o32-time-o1-space-easy-explana-xim3 | 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 | Garv_Virmani | NORMAL | 2024-08-22T02:12:29.346987+00:00 | 2024-08-22T02:12:29.347017+00:00 | 7,120 | 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```cpp []\nclass Solution {\npublic:\n int findComplement(int num) {\n int i = 0, ans = 0;\n while (num) {\n int temp = num & 1;\n if (!temp)\n ans += pow(2, i);\n num = num >> 1;\n i++;\n }\n return ans;\n }\n};\n``` | 17 | 4 | ['C++'] | 5 |
number-complement | Easy C++ | easy-c-by-rtom09-7la8 | Thought process is that you have to keep one number shift to left until it can no longer be shifted. At the same time, you can right shift by 1 for a number i a | rtom09 | NORMAL | 2017-01-10T18:21:46.559000+00:00 | 2017-01-10T18:21:46.559000+00:00 | 4,609 | false | Thought process is that you have to keep one number shift to left until it can no longer be shifted. At the same time, you can right shift by 1 for a number i and take the XOR, which leads to the opposite complement.\n\n```\nclass Solution {\npublic:\n int findComplement(int num) {\n int copy = num;\n int i = 0;\n\n while(copy != 0) {\n copy >>= 1;\n num ^= (1<<i);\n i += 1;\n }\n return num;\n }\n};\n``` | 17 | 1 | ['Bit Manipulation', 'C'] | 1 |
number-complement | Oneline C++ Solution | oneline-c-solution-by-kevin36-hlrj | ~~For some strange reason when I submit it fails the last test case,but if you run that test on its own in the custom testcase it passes. So I think something i | kevin36 | NORMAL | 2017-01-08T05:02:55.445000+00:00 | 2017-01-08T05:02:55.445000+00:00 | 6,016 | false | ~~For some strange reason when I submit it fails the last test case,but if you run that test on its own in the custom testcase it passes. So I think something is wrong with the testing.~~\n\n```class Solution {\npublic:\n int findComplement(int num) {\n return ~num & ((1 <<(int)log2(num))-1);\n }\n}; | 15 | 1 | [] | 7 |
number-complement | Work of art | work-of-art-by-ryanbaker1228-wdtc | Intuition\nThis is a work of art and if you disagree it\'s your fault.\nRespectfully, me\n\n# Approach\nGod invaded my head\n\n# Complexity\n- Time complexity:\ | ryanbaker1228 | NORMAL | 2024-08-22T01:39:11.635372+00:00 | 2024-08-22T01:39:11.635416+00:00 | 1,121 | false | # Intuition\nThis is a work of art and if you disagree it\'s your fault.\nRespectfully, me\n\n# Approach\nGod invaded my head\n\n# Complexity\n- Time complexity:\nWho cares its cool\n\n- Space complexity:\nWho cares its cool\n\n# Code\n```c []\nint findComplement(int num)\n{\n int n = num; return ~n & ((num |= (num |= (num |= (num |= (num |= num >> 1) >> 2) >> 4) >> 8) >> 16));\n}\n``` | 13 | 0 | ['C'] | 8 |
number-complement | Beat 100% -> 0ms | C++ | T.C. -> O(logn) | S.C. -> O(1) | beat-100-0ms-c-tc-ologn-sc-o1-by-abhishe-g550 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires finding the complement of a given integer num, where the complemen | abhishek_k11 | NORMAL | 2024-08-22T00:05:54.988152+00:00 | 2024-08-22T00:26:37.032042+00:00 | 1,709 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires finding the complement of a given integer num, where the complement is obtained by flipping all bits in the binary representation of num (i.e., converting 1s to 0s and 0s to 1s). The integer num will have no leading zeros.\n\n---\n\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Understanding the Binary Representation:**\n\n- The binary representation of num is a sequence of 1s and 0s.\nFor example, num = 5 has a binary representation 101.\n\n---\n\n\n2. **Finding the Highest Bit Set:**\n\n- The goal is to create a mask that has the same length as the binary representation of num but with all bits set to 1. This mask will help in flipping all bits of num.\n\n- The log2(num) function calculates the position of the highest bit set in num.\n\n- Shifting 1 left by the result of log2(num) gives us a number with only the highest bit set.\n\n- For num = 5 (binary 101), log2(5) returns 2, and 1 << 2 results in 100 (which is 4 in decimal).\n\n---\n\n\n3. **Creating the Mask:**\n\n- The next step is to create a mask where all bits are set to 1 up to the highest bit of num.\n\n- By doubling the result (multiplying by 2) and subtracting 1, we get a mask with all bits set to 1 in the positions that num occupies.\n\n- Continuing with num = 5 (binary 101), doubling 100 gives 1000 (binary for 8), and subtracting 1 gives 0111 (binary 7).\n\n---\n\n\n4. **Flipping the Bits:**\n\n- Finally, to get the complement of num, we XOR num with the mask. XORing with 1 flips the bit, and XORing with 0 keeps it the same.\nFor num = 5 (binary 101), XOR with 0111 results in 010, which is the binary for 2.\n\n---\n\n---\n\n\n\n# Complexity\n- Time complexity: O(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\n---\n\n---\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int findComplement(int n) {\n unsigned int highestBit = 1 << (int)(log2(n));\n unsigned int mask = (highestBit * 2) - 1;\n return n ^ mask;\n }\n};\n\n```\n\n | 13 | 2 | ['C++'] | 0 |
number-complement | ✅ Easy Solution with Explanation | 🛑2 Approaches🛑 | Without Bit Manipulation | 🔥Beats 100%🔥 | easy-solution-with-explanation-2-approac-ujl2 | See the pattern?\n\n\nNumber Binary Complement Complement Value\n1 = 1 -> 0 = 0\n\n2 = 10 -> 01 = 1\n3 | fxce | NORMAL | 2023-09-02T17:01:06.067756+00:00 | 2024-08-22T04:39:41.359531+00:00 | 1,374 | false | See the pattern?\n\n```\nNumber Binary Complement Complement Value\n1 = 1 -> 0 = 0\n\n2 = 10 -> 01 = 1\n3 = 11 -> 00 = 0\n\n4 = 100 -> 011 = 3\n5 = 101 -> 010 = 2\n6 = 110 -> 001 = 1\n7 = 111 -> 000 = 0\n\n8 = 1000 -> 0111 = 7\n9 = 1001 -> 0110 = 6\n10 = 1010 -> 0101 = 5\n11 = 1011 -> 0100 = 4\n12 = 1100 -> 0011 = 3\n13 = 1101 -> 0010 = 2\n14 = 1110 -> 0001 = 1\n15 = 1111 -> 0000 = 0\n.\n.\n.\n```\nThe range of binary numbers for n bits is from 0 to ($$2^n - 1$$). For example, with 1 bit we can represent 1, with 2 bits we can represent 2 (10) and 3 (11), with 3 bits we can represent 4 (100), 5 (101), 6 (110), 7 (111), and so on. The complement of a binary number can be found by subtracting the number itself from the maximum value in its binary representation, which is ($$2^n - 1$$).\n\nTo represent 1 we need at least 1 bit so, n = 1\n1 = ($$2^n -1$$) - number itself => 1 - 1 = 0 (Complement value)\n\nTo represent 2 and 3 we need at least 2 bits so, n = 2\n2 = ($$2^n -1$$) - number itself => 3 - 2 = 1 (Complement value)\n3 = ($$2^n -1$$) - number itself => 3 - 3 = 0 (Complement value)\n.\n.\n.\nsimilarly, To represent 15 we need at least 4 bits so, n = 4\n15 = ($$2^n -1$$) - number itself => 15 - 15 = 0 (Complement value)\n.\n.\n.\nand so on.\n\n\nThe max range value can be calculated with this `int tmp = (int) (Math.pow(2,digits(num))-1);`\n\nNow subtract the number from which we need to find the complement. `int res = tmp - num;` This will give us the complement of the number.\n\n\n# Approach 1: Using Binary Number Range, Without Bit Manipulation \n\n- Time complexity: O(log n)\n- Space complexity: O(1)\n\n```\nclass Solution {\n public int findComplement(int num) {\n int tmp = (int) (Math.pow(2,digits(num))-1);\n return tmp - num;\n }\n\n static int digits(int n){\n int count = 0;\n while(n > 0){\n n = n/2;\n count++;\n }\n return count;\n }\n}\n```\n\n\n# Approach 2: Optimizing Approach 1\n- Time complexity: O(1)\n- Space complexity: O(1)\n\n```\nclass Solution {\n public int findComplement(int num) {\n // Calculate the number of bits required to store the num\n long digits = (long) (Math.log(num) / Math.log(2)) + 1;\n \n // Calculate (2 ^ digits) - 1\n long tmp = (long) Math.pow(2, digits) - 1;\n \n // Subtract num from this value to get the complement\n return (int) tmp - num;\n }\n}\n```\n\n\n# Approach 3: Bit Manipulation\n\n- Time complexity: O(1)\n- Space complexity: O(1)\n\n```\nclass Solution {\n public int findComplement(int num) {\n\t return ~num & (Integer.highestOneBit(num) - 1);\n }\n}\n``` | 12 | 0 | ['Bit Manipulation', 'Java'] | 0 |
number-complement | ♾️ C++ | ✅100% Beats | ✅Full Explanation | 476. Number Complement | c-100-beats-full-explanation-476-number-ff3j7 | :) Please Upvote If You Like the Solution :)\n\n# Approach\n1. We know that we need to complement. For that we need to change 0 to 1 and 1 to 0.\n\n2. We need t | AnantKumawat22 | NORMAL | 2023-05-26T13:30:11.904989+00:00 | 2023-05-26T13:30:11.905022+00:00 | 894 | false | # :) Please Upvote If You Like the Solution :)\n\n# Approach\n1. We know that we need to complement. For that we need to change `0` to `1` and `1` to `0`.\n\n2. We need to think, what can we use here from our bitwise operators `(i.e &, |, ^, ~)`.\n\n3. Suppose we have,\n\n```\nEx. n = 10, binary-> 1010\n 1 0 1 0\n x x x x\n -----------\n 0 1 0 1\n\n```\n4. Think if we `xor` the `n` with `1111 (mask)`, we will get our desired answer. Like, \n\n```\n 1 0 1 0\n 1 1 1 1 ==> mask\n ----------- ==> XOR\n 0 1 0 1\n```\n\n5. Now we just need to make `mask`, for that we can take `1` and do `(left shit + add one)` to make it `1111`. Like, \n\n```\nmask -> 0 0 0 1 \n 0 0 1 0 ==> left shift (mask << 1)\n 0 0 1 1 ==> add 1 (mask + 1)\n```\n\n6. we know that if we do `&` of `n` with `1111` then we will get that `n` itself.\n\n7. so we will do the `5th step` until `((mask & n) != n)`.\n\n8. At last we can able to make `1111 (mask)` and now return `(mask ^ n)`, see `4th step`. \n\n# Complexity\n- Time complexity: O(ceil(log(n)))\n- Space complexity: O(1)\n\n**Why Time complexity: O(ceil(log(n)))???**\n\n1. we are running the while loop for the number of bit of n. \n n = 2^x ==> (x = number of bits).\n Ex. n = 10, binary -> 1 0 1 0 (4 bits)\n 10 = 2^x\n log2(10) = x\n ceil (log2(10)) = x, \n\n2. log2(10) == 3.322, but we represent 10 in 4 bits so take ceil value.\n# Code\n```\nclass Solution {\npublic:\n int findComplement(int num) {\n int mask = 1;\n \n while((mask & num) != num){\n mask = mask << 1;\n mask += 1;\n }\n return mask ^ num;\n }\n};\n``` | 11 | 0 | ['Bit Manipulation', 'C', 'Bitmask', 'C++'] | 0 |
number-complement | [C++] O(1) using bitwise operator with explanation | c-o1-using-bitwise-operator-with-explana-tw2o | \n/*\nnum = 00000110\nmask = 00000111\n~num = 11111001\nmask & ~num = 00000001\n*/\nint findComplement( int num ) {\n\tint mask = 0, t | sonugiri | NORMAL | 2020-05-04T07:33:43.006195+00:00 | 2020-05-04T07:41:09.299846+00:00 | 1,992 | false | ```\n/*\nnum = 00000110\nmask = 00000111\n~num = 11111001\nmask & ~num = 00000001\n*/\nint findComplement( int num ) {\n\tint mask = 0, tmp=num;\n\twhile( tmp ) {\n\t\ttmp = tmp >> 1;\n\t\tmask = mask << 1;\n\t\tmask = mask | 1;\n\t}\n\treturn ~num & mask;\n}\n``` | 11 | 0 | [] | 10 |
number-complement | Python XOR one line - no loops | python-xor-one-line-no-loops-by-w2schmit-x8vn | \nreturn num ^ (2**num.bit_length() - 1)\n | w2schmitt | NORMAL | 2019-07-01T04:29:08.634800+00:00 | 2019-07-01T04:31:33.799954+00:00 | 880 | false | ```\nreturn num ^ (2**num.bit_length() - 1)\n``` | 11 | 0 | ['Bit Manipulation', 'Python'] | 2 |
number-complement | Easy and simplest aproach , Easy to understand | easy-and-simplest-aproach-easy-to-unders-x0od | 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 | raeezrazz | NORMAL | 2024-08-22T04:56:27.848659+00:00 | 2024-08-22T04:56:27.848717+00:00 | 1,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. -->\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```javascript []\n/**\n * @param {number} num\n * @return {number}\n */\nvar findComplement = function(num) {\n let b = num.toString(2).split(\'\')\n for(let i = 0 ; i < b.length ; i++){\n if(b[i]== \'1\'){\n b[i]=\'0\'\n }else{\n b[i]=\'1\'\n }\n }\n console.log(b)\n return parseInt(b.join(\'\'),2)\n \n};\n``` | 10 | 5 | ['TypeScript', 'JavaScript'] | 3 |
number-complement | Easy Solution | Beats 100% | easy-solution-beats-100-by-sachinonly-8tlk | Code\npython []\nclass Solution(object):\n def findComplement(self, num):\n def decimal_to_binary(n):\n if n == 0:\n return | Sachinonly__ | NORMAL | 2024-08-22T00:15:38.315306+00:00 | 2024-08-22T00:15:38.315326+00:00 | 6,058 | false | # Code\n```python []\nclass Solution(object):\n def findComplement(self, num):\n def decimal_to_binary(n):\n if n == 0:\n return "0"\n binary = ""\n while n > 0:\n binary = str(n % 2) + binary\n n = n // 2\n return binary\n\n def binary_to_decimal(binary_str):\n decimal = 0\n binary_str = binary_str[::-1] # Reverse the string to process from right to left\n for i in range(len(binary_str)):\n decimal += int(binary_str[i]) * (2 ** i)\n return decimal\n\n binary = decimal_to_binary(num)\n n = len(binary)\n\n complement = \'\'\n for i in range(n):\n if binary[i] == \'0\':\n complement += \'1\'\n else:\n complement += \'0\'\n\n return binary_to_decimal(complement) \n```\n```C++ []\nclass Solution {\npublic:\n int findComplement(int num) {\n auto decimal_to_binary = [](int n) {\n if (n == 0) return std::string("0");\n std::string binary = "";\n while (n > 0) {\n binary = std::to_string(n % 2) + binary;\n n = n / 2;\n }\n return binary;\n };\n\n auto binary_to_decimal = [](const std::string &binary_str) {\n int decimal = 0;\n int n = binary_str.length();\n for (int i = 0; i < n; ++i) {\n if (binary_str[n - i - 1] == \'1\') {\n decimal += (1 << i); // Equivalent to 2^i\n }\n }\n return decimal;\n };\n\n std::string binary = decimal_to_binary(num);\n int n = binary.length();\n\n std::string complement = "";\n for (int i = 0; i < n; ++i) {\n if (binary[i] == \'0\') {\n complement += \'1\';\n } else {\n complement += \'0\';\n }\n }\n\n return binary_to_decimal(complement);\n }\n};\n```\n```Java []\nclass Solution {\n public int findComplement(int num) {\n String binary = decimalToBinary(num);\n int n = binary.length();\n\n StringBuilder complement = new StringBuilder();\n for (int i = 0; i < n; i++) {\n if (binary.charAt(i) == \'0\') {\n complement.append(\'1\');\n } else {\n complement.append(\'0\');\n }\n }\n\n return binaryToDecimal(complement.toString());\n }\n\n private String decimalToBinary(int n) {\n if (n == 0) return "0";\n StringBuilder binary = new StringBuilder();\n while (n > 0) {\n binary.insert(0, n % 2);\n n = n / 2;\n }\n return binary.toString();\n }\n\n private int binaryToDecimal(String binaryStr) {\n int decimal = 0;\n int n = binaryStr.length();\n for (int i = 0; i < n; i++) {\n if (binaryStr.charAt(n - i - 1) == \'1\') {\n decimal += Math.pow(2, i);\n }\n }\n return decimal;\n }\n}\n```\n\n | 10 | 0 | ['Bit Manipulation', 'Python', 'C++', 'Java', 'Python3'] | 4 |
number-complement | 2 ways to solve in Javascript | 2-ways-to-solve-in-javascript-by-yeuhoah-qbnd | Code\n\n/**\n * @param {number} num\n * @return {number}\n */\nvar findComplement = function(num) {\n // -- Solution 1:\n // let s = num.toString(2);\n | yeuhoahuuco | NORMAL | 2024-04-09T09:05:32.747299+00:00 | 2024-04-09T09:05:32.747342+00:00 | 285 | false | # Code\n```\n/**\n * @param {number} num\n * @return {number}\n */\nvar findComplement = function(num) {\n // -- Solution 1:\n // let s = num.toString(2);\n // let s1 = \'\';\n // for(let i = 0; i < s.length; i++)\n // {\n // s1 += (s[i] == \'0\') ? \'1\' : \'0\';\n // }\n // return parseInt(s1, 2);\n\n\n // -- Solution 2:\n let binaryString = num.toString(2);\n let complementChars = [];\n\n for (let i = 0; i < binaryString.length; i++) {\n complementChars.push((binaryString[i] === \'0\') ? \'1\' : \'0\');\n }\n\n let complementBinary = complementChars.join(\'\');\n return parseInt(complementBinary, 2);\n};\n``` | 10 | 0 | ['JavaScript'] | 3 |
number-complement | [Python] O(1) solution, explained | python-o1-solution-explained-by-dbabiche-xzdl | There is very smart solution, where we spread the highest 1-bit onto all the lower bits. Try to do the following operations, see https://leetcode.com/problems/n | dbabichev | NORMAL | 2021-12-27T08:22:36.361024+00:00 | 2021-12-27T08:22:36.361054+00:00 | 542 | false | There is very smart solution, where we spread the highest 1-bit onto all the lower bits. Try to do the following operations, see https://leetcode.com/problems/number-of-1-bits/discuss/1044775/python-n-and-(n-1)-trick-explained for more details, idea is similar.\n\n#### Complexity\nIt is just `5` operations we need to do here.\n\n#### Code\n```python\nclass Solution(object):\n def findComplement(self, num):\n mask = num\n mask |= mask >> 1\n mask |= mask >> 2\n mask |= mask >> 4\n mask |= mask >> 8\n mask |= mask >> 16\n return num ^ mask\n```\n\n#### Remark\nAnother solutions:\n\nWe can just find length of number `k` and subtract number from `2^k-1`.\n\nWe can also use `x & (x-1)` trick, and delete ones from the end one by one until we reach power of two (we need to make step if `x & (x-1)` is not equal to zero). When we reached power of two `s`, we evaluate \n`(2s+1) ^ num`. Complexity is `O(q)`, where `q` is number of non-zero bits.\n\nIf you have any question, feel free to ask. If you like the explanations, please **Upvote!** | 10 | 2 | ['Bit Manipulation'] | 1 |
number-complement | Possibly, the easiest way (Java) | possibly-the-easiest-way-java-by-akimovv-sxtz | Just replace and that\'s it\n\nclass Solution {\n public int findComplement(int num) {\n String binary = Integer.toBinaryString(num);\n binary | akimovve | NORMAL | 2020-05-06T09:57:19.441010+00:00 | 2020-05-06T09:57:19.441046+00:00 | 571 | false | Just replace and that\'s it\n```\nclass Solution {\n public int findComplement(int num) {\n String binary = Integer.toBinaryString(num);\n binary = binary\n .replace("0", "2")\n .replace("1", "0")\n .replace("2", "1");\n return Integer.parseInt(binary, 2);\n }\n}\n``` | 10 | 1 | ['Java'] | 0 |
number-complement | TypeScript, Runtime 42 ms Beats 100.00%, Memory 50.24 MB Beats 85.25% | typescript-runtime-42-ms-beats-10000-mem-78nq | Intuition\nThe intuition behind this solution is to directly flip all the bits of the binary representation of num using a mask. The mask is created by setting | r9n | NORMAL | 2024-08-22T00:10:51.803982+00:00 | 2024-08-22T00:10:51.804001+00:00 | 46 | false | # Intuition\nThe intuition behind this solution is to directly flip all the bits of the binary representation of num using a mask. The mask is created by setting all bits to 1 up to the highest bit of num. XORing num with this mask effectively inverts all the bits, giving the complement. This approach minimizes operations, ensuring both time and space efficiency.\n\n# Approach\nOverall, this approach provides a quick and memory-efficient way to find the binary complement, making it ideal for performance-critical applications.\n\n# Complexity\n- Time complexity:\nThe time complexity remains O(1), but with fewer operations for mask generation, this method should offer better runtime performance.\n\n- Space complexity:\nThe space complexity O(1) is constant because the amount of memory required by the algorithm does not depend on the size of the input (num). The memory usage is fixed and does not grow with the input.\n\n# Code\n```typescript []\nfunction findComplement(num: number): number {\n // Create the mask by finding the smallest power of 2 greater than num and subtracting 1\n const mask = (1 << (num.toString(2).length)) - 1;\n\n // XOR num with mask to get the complement\n return num ^ mask;\n}\n\n``` | 9 | 0 | ['TypeScript'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.