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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
longest-substring-without-repeating-characters | Swift Time Exceeded Fix | swift-time-exceeded-fix-by-vladinecko-eldj | The "optimized" solution still runs over the acceptable time limit when the solution is delivered in Swift. I did a quick profiling session and realized the pro | vladinecko | NORMAL | 2019-05-07T06:51:05.943333+00:00 | 2019-05-07T06:54:31.790886+00:00 | 993 | false | The "optimized" solution still runs over the acceptable time limit when the solution is delivered in Swift. I did a quick profiling session and realized the problem is in Swift\'s implementation of String and how it accesses information about the underlying characters. \n\n\n\nIf you\'re accessing the string to get the current character inside your loop, you will be making a ton of calls to String internals, which are currently super slow. The easiest way to circumvent that without having to convert the string into an array is to use String\'s iterator. Below is my implementation that could be optimized further but is already running faster than ~90% of submissions. \n\n```\nfunc longestSubstringLengthOptimized(_ string: String) -> Int {\n\tguard string.count > 0 else {\n\t\treturn 0\n\t}\n\n\tvar charIndexes = [Character:Int]()\n\tvar i = 0\n\tvar j = 0\n\tvar maxLength = 1\n\n\tfor currentChar in string {\n\t\tif let index = charIndexes[currentChar] {\n\t\t\tmaxLength = max(maxLength, j - i)\n\t\t\ti = max(i, index)\n\t\t}\n\t\tj += 1\n\t\tcharIndexes[currentChar] = j\n\t}\n\n\treturn max(maxLength, j - i)\n}\n``` | 18 | 0 | [] | 3 |
longest-substring-without-repeating-characters | [Dynamic Size Sliding Window Tutorial] Longest Substring Without Repeating Characters | dynamic-size-sliding-window-tutorial-lon-sn6u | Topic : Sliding Window\nSliding Window problems are problems in which a fixed or variable-size window is moved through a data structure, typically an array or | never_get_piped | NORMAL | 2024-06-21T05:22:19.723398+00:00 | 2024-06-27T07:09:58.302033+00:00 | 5,174 | false | **Topic** : Sliding Window\nSliding Window problems are problems in which a fixed or variable-size window is moved through a data structure, typically an array or string, to solve problems efficiently based on continuous subsets of elements. This technique is used when we need to find subarrays or substrings according to a given set of conditions. (GFG Reference)\n\nThere are two types of sliding window:\n- Fixed Size Sliding Window\n- Dynamic Size Sliding Window\n\n___\n\n## Dynamic Size Sliding Window\nA **Dynamic Size Sliding Window** refers to a window or subarray whose size is not fixed; instead, it dynamically expands or shrinks based on whether it meets specified conditions.\n\n## Intuition Behind Dynamic Size Sliding Window\nGenerally, questions involving sliding window techniques often inquire about the number of subarrays or substrings that satisfy specific conditions.\n\nBy using brute force, we enumerate all subarrays or substrings and check whether each satisfies the condition. This enumeration typically results in at least `O(n^2)` time complexity.\n\nFor a fixed variable `L`, we check all subarrays `[L : R]` where `L \u2264 R`. The sliding window technique can be applied when all subarrays `[L : M]` satisfy the condition, and all subarrays with a left bound \'L\' and any right bound `[M + 1 : R]` fail the condition.\n\nLet\'s assume our current window has the range `[L : R]`. If the subarray `[L : R + 1]` satisfies the condition, we can continue expanding the right pointer `R` to find the maximum `M` for the current fixed `L`. If `[L : R + 1]` fails the condition, there is no need to check `[L : R + n]` because all subsequent subarrays will also fail the condition. Now it is time to expand the left pointer.\n\n## Solution\nFirst, it\'s essential to determine whether the sliding window technique is applicable. This method is suitable when:\n```\nThe sliding window technique can be applied when all subarrays `[L : M]` satisfy the condition, and all subarrays with a left bound \'L\' and any right bound `[M + 1 : R]` fail the condition.\n```\nThis question satisfies these criteria, making it suitable for applying the sliding window technique.\n\nWe initialize a variable `count` to keep track of the frequency of each character within our window. We use a for-loop to expand the index `i` as the right pointer while it satisfies the condition. If `count[s[i]] > 1`, it indicates that the current window fails the condition, and we need to expand the left pointer. While moving the pointers, we continuously update the frequency of each character and our answer as necessary.\n\n\n\n<br/><br/>\n\n\n```c++ []\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n int ans = 0;\n vector<int> count(256);\n for(int i = 0, j = 0; i < s.size(); i++) {\n count[s[i]]++;\n while(count[s[i]] > 1) {\n count[s[j++]]--;\n }\n ans = max(ans, i - j + 1);\n }\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n int ans = 0;\n int[] count = new int[256];\n for (int i = 0, j = 0; i < s.length(); i++) {\n count[s.charAt(i)]++;\n while (count[s.charAt(i)] > 1) {\n count[s.charAt(j++)]--;\n }\n ans = Math.max(ans, i - j + 1);\n }\n return ans;\n }\n}\n```\n```python []\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n ans = 0\n count = [0] * 256\n j = 0\n for i in range(len(s)):\n count[ord(s[i])] += 1\n while count[ord(s[i])] > 1:\n count[ord(s[j])] -= 1\n j += 1\n ans = max(ans, i - j + 1)\n return ans\n```\n```Go []\nfunc lengthOfLongestSubstring(s string) int {\n ans := 0\n count := make([]int, 256)\n for i, j := 0, 0; i < len(s); i++ {\n count[s[i]]++\n for count[s[i]] > 1 {\n count[s[j]]--\n j++\n }\n if i-j+1 > ans {\n ans = i - j + 1\n }\n }\n return ans\n}\n```\n```PHP []\nclass Solution {\n\n /**\n * @param String $s\n * @return Integer\n */\n function lengthOfLongestSubstring($s) {\n $ans = 0;\n $count = array_fill(0, 256, 0);\n $j = 0;\n for ($i = 0; $i < strlen($s); $i++) {\n $count[ord($s[$i])]++;\n while ($count[ord($s[$i])] > 1) {\n $count[ord($s[$j++])]--;\n }\n $ans = max($ans, $i - $j + 1);\n }\n return $ans;\n }\n}\n```\n```javascript []\n/**\n * @param {string} s\n * @return {number}\n */\nvar lengthOfLongestSubstring = function(s) {\n let ans = 0;\n let count = new Array(256).fill(0);\n for (let i = 0, j = 0; i < s.length; i++) {\n count[s.charCodeAt(i)]++;\n while (count[s.charCodeAt(i)] > 1) {\n count[s.charCodeAt(j++)]--;\n }\n ans = Math.max(ans, i - j + 1);\n }\n return ans;\n};\n```\n\n\n**Complexity**:\n* Time Complexity : `O(n)`\n* Space Complexity : `O(1)`\n\n**Feel free to leave a comment if something is confusing, or if you have any suggestions on how I can improve the post.** | 17 | 0 | ['C', 'PHP', 'Python', 'Java', 'Go', 'JavaScript'] | 6 |
longest-substring-without-repeating-characters | C++ || Sliding Window || Keeping it S!mple | c-sliding-window-keeping-it-smple-by-pri-7rkb | \nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n unordered_set<char>sub;//set to store occoured character\n int left=0, | priyamesh28 | NORMAL | 2021-09-06T18:02:38.541872+00:00 | 2021-09-06T18:02:38.541925+00:00 | 1,230 | false | ```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n unordered_set<char>sub;//set to store occoured character\n int left=0,right=0; //two pointers to navigate\n int max_size=0;\n while(left<s.size() && right<s.size())\n {\n //if the char is not in the subset\n //put it in the set\n //find the max size\n if(sub.find(s[right])==sub.end())\n {\n sub.insert(s[right]);\n int n=sub.size();\n max_size=max(max_size,n);\n right++;\n }\n //if already there \n //shrink the window from left \n //until the repeated char is not omitted from left\n else\n {\n sub.erase(s[left]);\n left++;\n }\n }\n return max_size;\n }\n};\n```\nIf you find any issue in understanding the solutions then comment below, will try to help you.\nIf you found my solution useful.\nSo please do upvote and encourage me to document all leetcode problems\uD83D\uDE03\nHappy Coding :) | 17 | 1 | ['C', 'Ordered Set'] | 1 |
longest-substring-without-repeating-characters | Go solution | go-solution-by-waydi1-9acj | \nfunc lengthOfLongestSubstring(s string) int {\n start := 0\n longest := 0\n used := map[byte]int{}\n \n for i := 0; i < len(s); i++ {\n | waydi1 | NORMAL | 2021-01-10T11:38:09.566724+00:00 | 2021-01-10T11:38:09.566755+00:00 | 1,998 | false | ```\nfunc lengthOfLongestSubstring(s string) int {\n start := 0\n longest := 0\n used := map[byte]int{}\n \n for i := 0; i < len(s); i++ {\n c := s[i]\n \n if _, ok := used[c]; ok && used[c] >= start {\n start = used[c] + 1\n }\n \n longest = max(longest, i - start + 1)\n used[c] = i\n }\n \n return longest\n}\n\nfunc max(a, b int) int {\n if a > b {\n return a\n }\n \n return b\n}\n``` | 17 | 0 | ['Go'] | 1 |
longest-substring-without-repeating-characters | [VIDEO] Visualization of O(n) Sliding Window Approach | video-visualization-of-on-sliding-window-evai | https://youtu.be/pY2dYa1m2VM\n\nA brute force solution would first require finding every possible substring, which would run in O(n2) time. We\'re not done yet | AlgoEngine | NORMAL | 2024-10-04T21:26:50.811575+00:00 | 2024-10-04T21:26:50.811595+00:00 | 2,128 | false | https://youtu.be/pY2dYa1m2VM\n\nA brute force solution would first require finding every possible substring, which would run in O(n<sup>2</sup>) time. We\'re not done yet though, because we now have to check every substring for duplicate characters by iterating through every substring. Each check for duplicate characters runs in O(n) time, and we need to do that for every substring generated (which ran in O(n<sup>2</sup>) time), so the brute force approach ends up running in O(n<sup>3</sup>) time.\n\nInstead, we can reduce this to O(n) time by using a sliding window approach and eliminating unnecessary computations. We use two pointers, `l` and `r`, to denote where the substring starts and ends, and a dictionary called `seen` to keep track of the index of each character encountered. Then, we move the right pointer one character at a time to the right to expand our substring.\n\nAt each iteration, we check for two things.\n1. Have we seen the newly added character (at index `r`) before? If we haven\'t, then this is a brand new character and we can just add it to the substring and extend the length\n2. If we have seen it before, is its last known position greater than or equal to the left index? If it is, then that means it\'s repeated somewhere in the substring. If not, then that means it\'s <i>outside</i> of the substring, so we can just add it to the substring and extend the length\n\nSo if both conditions are true, the new character is repeated and we have a problem. We can get rid of the repeated character by moving up the left pointer to be one index past the last recorded index in `seen`. Then, we just keep moving up the right pointer until it reaches the end of the string. Since we only have to loop through the string once, and since hash table lookups run in constant time, this algorithm ends up running in O(n) time.\n\nFor an intuitive proof of why this works and why we don\'t need to check all the other substrings while moving up the left pointer, please see the video - it\'s a bit difficult to explain without a visualization and a concrete example. But basically, all the other substrings will either still contain a repeated character or will be shorter than the last valid substring encountered, so they can be safely ignored.\n\n\n# Code\n```\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n seen = {}\n l = 0\n length = 0\n for r in range(len(s)):\n char = s[r]\n if char in seen and seen[char] >= l:\n l = seen[char] + 1\n else:\n length = max(length, r - l + 1)\n seen[char] = r\n\n return length\n```\n | 16 | 0 | ['Hash Table', 'String', 'Sliding Window', 'Python', 'Python3'] | 0 |
longest-substring-without-repeating-characters | C++|Sliding Window | Hash Map |O(n) | csliding-window-hash-map-on-by-xahoor72-b6qk | Intuition\n Describe your first thoughts on how to solve this problem. \nIdea is to use a map and check when there is a duplicate remove it and maintain the cou | Xahoor72 | NORMAL | 2023-02-09T19:05:43.489167+00:00 | 2023-02-10T08:36:53.609262+00:00 | 4,327 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIdea is to use a map and check when there is a duplicate remove it and maintain the counter for max window size.\nThis tempate ca be used for multiple questions like:\n- https://leetcode.com/problems/maximum-erasure-value/description/\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSo using Sliding Window These are the steps:\n\n- Insert one by one in map and also check a condition along with this .\n- Condition is if mp[s[i]] is >1 i.e is a duplicate so remove it .\n- Keep a maxi varaible for maximum window size.\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(128) --> can be taken as constant or surely less than using a map direclty\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n int n=s.size(),j=0,ans=0,maxi=0;\n \n vector<int>mp(128,0);\n for(int i=0;i<n;i++){\n if(!mp[s[i]]++)maxi++;\n while(mp[s[i]]>1){\n mp[s[j]]--;\n j++;\n }\n ans=max(ans,i-j+1);\n }\n return ans;\n \n }\n};\n```\n# UpVote will Be Apprecaited \uD83D\uDD3C\uD83D\uDD3C\uD83D\uDD3C | 16 | 1 | ['Hash Table', 'String', 'Sliding Window', 'C++'] | 5 |
longest-substring-without-repeating-characters | python | python-by-vote4-w202 | \ndef lengthOfLongestSubstring(self, s: str) -> int:\n maxLength = 0\n dict = {}\n\n i,j = 0,0\n n = len(s)\n\n while(j < n): | vote4 | NORMAL | 2022-09-19T05:33:03.433631+00:00 | 2022-09-19T05:33:03.433679+00:00 | 1,115 | false | ```\ndef lengthOfLongestSubstring(self, s: str) -> int:\n maxLength = 0\n dict = {}\n\n i,j = 0,0\n n = len(s)\n\n while(j < n):\n c = s[j] \n \n dict[c] = 1 if not c in dict else dict[c] + 1\n \n \n if dict[c] > 1:\n while(dict[c] > 1):\n dict[s[i]] -= 1\n i += 1\n \n maxLength = max(maxLength, j - i + 1)\n j += 1\n\n return maxLength\n``` | 16 | 2 | [] | 1 |
longest-substring-without-repeating-characters | O(n) Solution in C++ || Sliding Window || HashMaps | on-solution-in-c-sliding-window-hashmaps-icsg | The idea here is pretty simple... we use a map to keep track of already visited characters...\nWe initialize another pointer (j) which gives us the starting ind | harshit7962 | NORMAL | 2022-06-10T03:04:47.835554+00:00 | 2022-06-10T03:48:28.810307+00:00 | 2,084 | false | The idea here is pretty simple... we use a map to keep track of already visited characters...\nWe initialize another pointer (j) which gives us the starting index of current window and we traverse through the string using pointer i, which indicated current index of our window...\n* If the character at ith index is not present in our map, we simply add it to our map and continue the iteration...\n* If the character at ith index is already present, but its index does not lie in our window, it implie that current character is not part of our current string and hence we update its index value in our map and continue with the iteration...\n* If the character at ith index is already present and the index at which it is present lies in our current window, then we update the starting index of current window as i value and our window is now a new window with size 1...\n\nWe keep track of our longest length using res variable in each iteration...\n\n*Here amortized TC is O(n), considering map searching is O(1), to get actual O(1) searching TC, we can use vector of size 128 to store our characters...*\n\n**Pls upvote this thread if you found the solution helpful**\n\n\n```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n if(s.size()<=1) return s.size();\n \n map<char, int> mp;\n int curr=0, res=0;\n for(int i=0;i<s.size();i++) {\n\t\t\t//i-curr, gives us the count of characters in our current window (curr is starting of our window)\n res=max(res, i-curr);\n\t\t\t\n\t\t\t//If the character is present and its index is present in current window, we update our current window...\n if(mp.find(s[i])!=mp.end() && mp[s[i]]>=curr) {\n curr = mp[s[i]]+1;\n }\n mp[s[i]] = i;\n }\n\t\t\n\t\t//This is to handle the case when the longest substring is at the end our string, in this case we wont enter the if condition and hence curr variable won\'t be updated...\n if(res<s.size()-curr) return s.size()-curr;\n\t\t\n return res;\n }\n``` | 16 | 2 | ['C', 'Sliding Window', 'C++'] | 1 |
longest-substring-without-repeating-characters | Javascript Solution using Sliding Window in O(n) time (w/ explanation) | javascript-solution-using-sliding-window-t4qi | Explanation\n\nThe main method used for this problem is the sliding window technique. The sliding window is essentially 2 pointers that will help to keep track | AmehPls | NORMAL | 2021-11-26T17:15:27.163067+00:00 | 2021-11-27T16:39:19.058158+00:00 | 2,057 | false | ## Explanation\n\nThe main method used for this problem is the **sliding window** technique. The sliding window is essentially 2 pointers that will help to keep track the start and end of a substring. In this solution, this window will always contain a substring with no duplicate characters.\n\nHere are the brief steps of my solution:\n\n1. We initialize the variables maxLength, which keeps track of the current longest length of any substring in the string, and left, which is the start of the substring currently being tracked. A set is also initialised to keep track of the elements in a substring. Since there are no duplicate characters in the substring (unique), a set will be a perfect tool to keep track of duplicates.\n\n2. We iterate through this loop using a right pointer. As this right pointer moves, we first check if the char at the right pointer is a duplicate of any previous characters in the substring by cross checking with the set.\n\n3. If the set already has the character, the set will continuously remove the leftmost char s[left] while also shifting the left pointer to the right. This will shrink the window size until there are no more duplicates characters.\n\n4. Once it is ensured that there are no duplicate characters, it will add the right most char s[right] to the set and update maxLength if this new substring is longer than a previous substring.\n\n## Performance\n\nThe time complexity of this solution is linear, **O(n)**, since we solved the problem by having to pass through the string only once.\n\nHere are the details of my submission:\nRuntime: 96 ms, faster than 89.62% \nMemory Usage: 43.3 MB, less than 74.80% \n\n## Code\n\n```\nvar lengthOfLongestSubstring = function(s) {\n var maxLength = 0\n var left = 0\n var charSet = new Set()\n \n for (var right = 0; right < s.length; right++){\n while (charSet.has(s[right])){\n charSet.delete(s[left])\n left += 1\n }\n charSet.add(s[right])\n maxLength = Math.max(maxLength, right - left + 1)\n }\n \n return maxLength\n};\n```\n\nI hope this helps! Do let me know if there are any lapses in my explanation and/or if my solution can be improved in any way :) | 16 | 1 | ['Sliding Window', 'Ordered Set', 'JavaScript'] | 1 |
longest-substring-without-repeating-characters | 10-line O(n) easy Java solution, covering edge cases without extra code | 10-line-on-easy-java-solution-covering-e-8m04 | This problem is a basic sliding window problem, so we should have a left and a right index. We will let our right index be the iterator of the string and hold t | gargeemukherjee | NORMAL | 2021-06-07T11:35:40.848217+00:00 | 2021-06-07T11:55:15.535984+00:00 | 1,854 | false | This problem is a basic sliding window problem, so we should have a left and a right index. We will let our right index be the iterator of the string and hold the position of the current character we are at. The basic idea is to put the characters you visit in map with their index as the value. We want to find the last occurrence, not the frequency of occurence. \nOnce we find the character in map, we recalculate max by taking the max value of max and right - left ( length of sliding window in last occurrence, before we found a repeating character), and we recalculate left by taking max of left and the last index our character was found in.\n\n``` \n public int lengthOfLongestSubstring(String s) {\n int right, left = 0, max = 0;\n HashMap<Character, Integer> map = new HashMap<>();\n for(right = 0; right < s.length(); right++) {\n if(map.containsKey(s.charAt(right))) {\n max = Math.max(max, right - left);\n left = Math.max(left, map.get(s.charAt(right)) + 1); \n } \n map.put(s.charAt(right), right);\n }\n return Math.max(max, right - left);\n } | 16 | 0 | ['Sliding Window', 'Java'] | 1 |
longest-substring-without-repeating-characters | share my javaScript solution,i think it is easy to understand | share-my-javascript-solutioni-think-it-i-uv15 | ```\nvar lengthOfLongestSubstring = function (s) {\n var max=0,\n theSub=\'\'\n for(var i=0;i=0){ \n theSub= theSub.substring(idx+1) \n | masicheng | NORMAL | 2019-06-14T07:22:34.455176+00:00 | 2019-06-24T01:54:42.798754+00:00 | 2,507 | false | ```\nvar lengthOfLongestSubstring = function (s) {\n var max=0,\n theSub=\'\'\n for(var i=0;i<s.length;i++){\n const idx=theSub.indexOf(s[i])\n theSub+=s[i]\n if(idx>=0){ \n theSub= theSub.substring(idx+1) \n }\n if(theSub.length>max){\n max=theSub.length\n }\n }\n return max\n}\n\t | 16 | 0 | ['JavaScript'] | 2 |
longest-substring-without-repeating-characters | O(N) runtime , constant space solution. | on-runtime-constant-space-solution-by-13-kbzd | \nKeep track of the last index of each char. Scan s from left to right, if hit a previously encountered char, then reset the longest substring to start just aft | 1337beef | NORMAL | 2014-09-25T17:57:37+00:00 | 2014-09-25T17:57:37+00:00 | 3,695 | false | \nKeep track of the last index of each char. Scan s from left to right, if hit a previously encountered char, then reset the longest substring to start just after the last index of the seen char.\n\n int lengthOfLongestSubstring(const string& s) {\n int idx[256]; // indices of each char.\n memset(idx,-1,sizeof idx);\n int i,j,best=0,start=0;\n for(i=0;i<s.size();i++){\n const unsigned char c=(unsigned char)s[i];\n j=idx[c];\n idx[c]=i;\n if(start<=j){\n start=j+1;\n }\n best=max(best,i-start+1);\n }\n return best;\n } | 16 | 0 | [] | 1 |
longest-substring-without-repeating-characters | Best Solution for Arrays 🚀 in C++, Python and Java || 100% working | best-solution-for-arrays-in-c-python-and-hekt | Intuition💡 To find the Longest Substring Without Repeating Characters, we use a sliding window approach. This method dynamically adjusts the window size to ensu | BladeRunner150 | NORMAL | 2025-01-11T05:54:56.103372+00:00 | 2025-01-11T05:54:56.103372+00:00 | 3,456 | false | # Intuition
💡 To find the **Longest Substring Without Repeating Characters**, we use a **sliding window** approach. This method dynamically adjusts the window size to ensure all characters inside the window are unique.
# Approach
👉 Use two pointers, `l` and `r`, to define a window over the string.
👉 Maintain a frequency array or set to track characters in the current window.
👉 Expand the window by moving `r`. If a duplicate is found, shrink the window by moving `l`.
👉 Track the maximum window size during this process.
# Complexity
- Time complexity: $$O(n)$$ 🔥
- Space complexity: $$O(1)$$ (fixed size for ASCII or Unicode) ✨
# Code
```cpp []
Code
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int ans = 0;
vector<int> arr(128, 0);
int l = 0;
for (int r = 0; r < s.length(); r++) {
int curr = s[r];
while (arr[curr] > 0) {
arr[s[l]]--;
l++;
}
arr[curr]++;
ans = max(ans, r - l + 1);
}
return ans;
}
};
```
```python []
Code
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
ans = 0
arr = [0] * 128
l = 0
for r in range(len(s)):
curr = ord(s[r])
while arr[curr] > 0:
arr[ord(s[l])] -= 1
l += 1
arr[curr] += 1
ans = max(ans, r - l + 1)
return ans
```
```java []
Code
class Solution {
public int lengthOfLongestSubstring(String s) {
int ans = 0;
int[] arr = new int[128];
int l = 0;
for (int r = 0; r < s.length(); r++) {
int curr = s.charAt(r);
while (arr[curr] > 0) {
arr[s.charAt(l)]--;
l++;
}
arr[curr]++;
ans = Math.max(ans, r - l + 1);
}
return ans;
}
}
```
<img src="https://assets.leetcode.com/users/images/7b864aef-f8a2-4d0b-a376-37cdcc64e38c_1735298989.3319144.jpeg" alt="upvote" width="150px">
# Connect with me on LinkedIn for more insights! 🌟 Link in bio | 15 | 0 | ['Hash Table', 'String', 'Sliding Window', 'Python', 'C++', 'Java', 'Python3'] | 0 |
longest-substring-without-repeating-characters | Python sliding window (simple syntax) | python-sliding-window-simple-syntax-by-g-1by8 | Python sliding window. \n\n\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n # create a window with left and right\n # keep | grapes42 | NORMAL | 2020-02-18T03:43:13.014802+00:00 | 2020-02-18T03:43:13.014850+00:00 | 2,039 | false | Python sliding window. \n\n```\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n # create a window with left and right\n # keep a hash of elements already added\n left = 0\n right = 0\n seen = {} # keeps track of seen elements\n\n max_count = 0\n\n for i, character in enumerate(s):\n if character not in seen or seen[character] < left: # notice this logic\n seen[character] = i\n right = i\n if (right - left + 1) > max_count: # update the largest count\n max_count = (right - left + 1)\n else:\n # we move start to one element after we found the character\n left = seen[character] + 1\n seen[character] = i # update index of last time we saw the character\n\n return max_count\n``` | 15 | 0 | ['Sliding Window', 'Python'] | 2 |
longest-substring-without-repeating-characters | Java | Sliding Window template | java-sliding-window-template-by-prashant-nzz9 | Algo:\n1. Use a hashMap to keep track of the latest index of each letter\n2. Keeping the left pointer at rest, move the right pointer by 1 letter at a time.\n3. | prashant404 | NORMAL | 2019-07-19T18:55:36.305442+00:00 | 2022-06-12T04:04:49.931852+00:00 | 4,967 | false | Algo:\n1. Use a hashMap to keep track of the latest index of each letter\n2. Keeping the left pointer at rest, move the right pointer by 1 letter at a time.\n3. When a repeating character is encountered, update the maxLength and move the left pointer to max{left pointer, old last occurence of this character as available in the map}. We do a max because we don\'t want to take the left pointer backwards at any time (e.g. in "abba"), it will only move forward or stay still.\n4. return max {right-left, maxLength}. Doing this outside the loop is essential as it handles strings with all unique chars.\n\n**T/S:** O(n)/O(a), where n = s.length, a = size of character set\n```\npublic int lengthOfLongestSubstring(String s) {\n\tvar left = 0;\n\tvar right = 0;\n\tvar maxLength = 0;\n\n\tfor (var map = new HashMap<Character, Integer>(); right < s.length();) {\n\t\tvar ch = s.charAt(right);\n\t\t\n\t\tif (map.containsKey(ch)) {\n\t\t\tmaxLength = Math.max(maxLength, right - left);\n\t\t\tleft = Math.max(left, map.get(ch) + 1);\n\t\t}\n\t\t\n\t\tmap.put(ch, right++);\n\t}\n\treturn Math.max(maxLength, right - left);\n}\n```\n\nA slight variation using the template for Sliding Window questions that can be used in:\n* https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters (P)\n* https://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters (P)\n* https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters\n* https://leetcode.com/problems/fruit-into-baskets\n* https://leetcode.com/problems/minimum-size-subarray-sum\n* https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters\n* https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold\n* https://leetcode.com/problems/distinct-numbers-in-each-subarray\n* https://leetcode.com/problems/diet-plan-performance\n* [1695. Maximum Erasure Value](https://leetcode.com/problems/maximum-erasure-value/discuss/2141049/Java-or-Sliding-Window-or-Reuse-LC-3)\n\nand various others\n\n\n```\npublic int lengthOfLongestSubstring(String s) {\n\tvar longest = Integer.MIN_VALUE;\n\tvar map = new HashMap<Character, Integer>();\n\n\tfor (int right = 0, left = 0, distinctChars = 0; right < s.length(); right++) {\n\t\tvar rightChar = s.charAt(right);\n\t\tmap.compute(rightChar, (k, v) -> v == null ? 1 : v + 1);\n\n\t\tif (map.get(rightChar) == 1) {\n\t\t\t// if this char is the first one in the window, update records \n\t\t\tlongest = Math.max(longest, right - left + 1);\n\t\t\tdistinctChars++;\n\t\t} else {\n\t\t // shrink window until window size becomes equal to number of distinct characters in it, i.e. all chars in the window are distinct\n\t\t\twhile (distinctChars != right - left + 1) {\n\t\t\t\tvar leftChar = s.charAt(left++);\n\t\t\t\tmap.put(leftChar, map.get(leftChar) - 1);\n\t\t\t\tif (map.get(leftChar) == 0)\n\t\t\t\t\tdistinctChars--;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn longest == Integer.MIN_VALUE ? 0 : longest;\n}\n```\n***Please upvote if this helps*** | 15 | 0 | ['Two Pointers', 'Sliding Window', 'Java'] | 2 |
longest-substring-without-repeating-characters | Accepted 16ms c++ DP solution, O(n), with bitmask to record the last position of each letter appears | accepted-16ms-c-dp-solution-on-with-bitm-9m2f | class Solution {\n public:\n int lengthOfLongestSubstring(std::string s) {\n std::vector<int> flag(256, -1);\n int start = 0, lo | prime_tang | NORMAL | 2015-05-30T11:40:10+00:00 | 2015-05-30T11:40:10+00:00 | 4,914 | false | class Solution {\n public:\n int lengthOfLongestSubstring(std::string s) {\n std::vector<int> flag(256, -1);\n int start = 0, longest = 0;\n for (int i = 0; i != s.size(); ++i) {\n start = std::max(start, flag[s[i]] + 1);\n flag[s[i]] = i;\n longest = std::max(longest, i - start + 1);\n }\n return longest;\n }\n };\n\nUpdated **Jun 30**: In fact, there is no need to update `longest` evey time:\n\n class Solution {\n public:\n int lengthOfLongestSubstring(std::string s) {\n std::vector<int> flag(256, -1);\n int start = 0, longest = 0, len = s.size();\n for (int i = 0; i != len; ++i) {\n if (flag[s[i]] >= start) {\n longest = std::max(longest, i - start);\n start = flag[s[i]] + 1;\n }\n flag[s[i]] = i;\n }\n return std::max(longest, len - start);\n }\n }; | 15 | 0 | [] | 3 |
longest-substring-without-repeating-characters | My simple c++ solution | my-simple-c-solution-by-kelseyzhou-ybbb | class Solution {\n public:\n int lengthOfLongestSubstring(string s) {\n vector<int> table(256, 0);\n int maxstr=0, track=0;\n for(int | kelseyzhou | NORMAL | 2016-02-24T16:49:13+00:00 | 2018-09-27T05:56:13.756352+00:00 | 4,847 | false | class Solution {\n public:\n int lengthOfLongestSubstring(string s) {\n vector<int> table(256, 0);\n int maxstr=0, track=0;\n for(int i=0;i<s.length();i++)\n {\n while(table[s[i]])table[s[track++]]=0;\n table[s[i]]=1;\n maxstr=max(maxstr, i-track+1);\n \n }\n return maxstr;\n }\n}; | 15 | 1 | [] | 1 |
longest-substring-without-repeating-characters | JavaScript True O(n) Sliding Window with Explanation | javascript-true-on-sliding-window-with-e-dcmk | Complexity\n- Time complexity: O(n)\n- Space complexity: O(n)\n\n# Code\n\n/**\n * @param {string} s\n * @return {number}\n */\nfunction lengthOfLongestSubstrin | danorati | NORMAL | 2022-12-22T21:07:58.058462+00:00 | 2022-12-22T21:12:50.901627+00:00 | 4,483 | false | # Complexity\n- Time complexity: O(n)\n- Space complexity: O(n)\n\n# Code\n```\n/**\n * @param {string} s\n * @return {number}\n */\nfunction lengthOfLongestSubstring(inputString) {\n if (inputString.length == 0) return 0;\n\n let n = inputString.length;\n \n // starting index of current window substring\n let stCurr = 0,\n // length of the longest substring\n longest = 0,\n // length of the current substring (size of window)\n currLen = 0,\n // starting index of longest substring\n start = 0;\n\n\t// hashmap to store the element as key and index last seen as value\n let lastSeenAt = {};\n\n // Traverse inputString to find the longest substring\n // without repeating characters.\n for (index = 0; index < n; index++) {\n let val = inputString[index];\n\n // If the current element is not present in the hash map,\n // then store it in the hash map with the value as the current index.\n if (!(val in lastSeenAt)) lastSeenAt[val] = index;\n else {\n // If the current element is present in the hash map,\n // it means that this element may have appeared before.\n // Check if the current element occurs before or after `stCurr`.\n if (lastSeenAt[val] >= stCurr) {\n currLen = index - stCurr;\n if (longest < currLen) {\n longest = currLen;\n start = stCurr;\n }\n // The next substring will start after the last\n // occurence of the current element.\n stCurr = lastSeenAt[val] + 1;\n }\n\n // Update the last occurence of\n // the element in the hash map\n lastSeenAt[val] = index;\n }\n }\n\n // Update the longest substring\'s\n // length and starting index.\n if (longest < index - stCurr) {\n start = stCurr;\n longest = index - stCurr;\n }\n\n return longest;\n};\n``` | 14 | 0 | ['JavaScript'] | 1 |
longest-substring-without-repeating-characters | Rust Two Pointers with HashMap | rust-two-pointers-with-hashmap-by-minami-w7ce | I like the HashMap.insert function returning the old value :)\nrust\nuse std::collections::HashMap;\n\nimpl Solution {\n pub fn length_of_longest_substring(s | Minamikaze392 | NORMAL | 2022-06-10T02:36:31.654305+00:00 | 2022-06-10T02:36:31.654352+00:00 | 1,016 | false | I like the HashMap.insert function returning the old value :)\n```rust\nuse std::collections::HashMap;\n\nimpl Solution {\n pub fn length_of_longest_substring(s: String) -> i32 {\n let mut hash: HashMap<char, i32> = HashMap::new();\n let mut ans = 0;\n let mut lo = -1;\n for (hi, ch) in s.chars().enumerate() {\n if let Some(i) = hash.insert(ch, hi as i32) {\n lo = lo.max(i);\n }\n ans = ans.max(hi as i32 - lo);\n }\n ans\n }\n}\n``` | 14 | 0 | ['Two Pointers', 'Rust'] | 1 |
longest-substring-without-repeating-characters | Java Simple Sliding Window Technique With Comments | java-simple-sliding-window-technique-wit-dlte | \n\n public int lengthOfLongestSubstring(String s) {\n int left = 0; // start of window\n int right = 0; // end of window (initially the same a | emerfan | NORMAL | 2021-12-15T09:27:46.842169+00:00 | 2021-12-15T09:28:12.806571+00:00 | 1,382 | false | ```\n\n public int lengthOfLongestSubstring(String s) {\n int left = 0; // start of window\n int right = 0; // end of window (initially the same as start so we can grab the first char)\n int result = 0; // var to store the length of the longest substring we have found so far\n HashSet<Character> chars = new HashSet(); // hashset to track the chars in the current substring\n\t\t// the right hand side of the window must not go over the bounds of the string\n while(right < s.length()) {\n // use the right hand side of the window to get the char, it is initialised to 0 so will pick the first character first\n if(!chars.contains(s.charAt(right))) {\n chars.add(s.charAt(right));\n\t\t\t\t// if the current set of unique chars is greater in size than the result, that\'s our longest substring\n result = Math.max(result, chars.size());\n\t\t\t\t// increment right to increase the window size and grab a new char\n right++;\n } else {\n\t\t\t// once we encounter a char which is already in the hashset we need create a new window starting from left + 1, and reset right to equal left to initialise a new window\n left ++;\n right = left;\n\t\t\t\t// reset our tracker\n chars.clear();\n }\n }\n return result;\n }\n\t``` | 14 | 0 | ['Sliding Window', 'Java'] | 3 |
longest-substring-without-repeating-characters | ScanLeft | Scala | Concise Solution with Explanation | scanleft-scala-concise-solution-with-exp-qkcz | We would use scanLeft starting with initial value empty string("")\nNow we for Binary Operator op: (B, A) => B, we would provide substring function that would s | imran-sarwar | NORMAL | 2020-08-14T17:25:25.802168+00:00 | 2020-08-14T18:48:16.151785+00:00 | 999 | false | We would use scanLeft starting with initial value empty string("")\nNow we for Binary Operator op: (B, A) => B, we would provide substring function that would substring till it would find current character in previously calculated String, and we postfix the current character to current substring to start looking for further character.\n```\ndef lengthOfLongestSubstring(s: String): Int = {\n\ts.scanLeft("")((currStr: String, currChar: Char) => \n\tcurrStr.substring(1 + currStr.indexOf(currChar)) + currChar)\n\t// Up to this point we would get vector like this\n\t// Vector(, a, ab, abc, bca, cab, abc, cb, b)\n\t// now if we take max of length would get the answer\n\t.map(_.length)\n\t.reduce(Math.max)\n}\n``` | 14 | 0 | ['Scala'] | 3 |
longest-substring-without-repeating-characters | O(N) C# Solution with simple code & explanation | on-c-solution-with-simple-code-explanati-muq2 | The idea is store index of each char in dictionary, if repeating char is encountered - start calculating from stored index, since there cannot be string greate | christris | NORMAL | 2019-02-27T02:46:09.739011+00:00 | 2019-02-27T02:46:09.739076+00:00 | 1,396 | false | The idea is store index of each char in dictionary, if repeating char is encountered - start calculating from stored index, since there cannot be string greater than string from character starting from any index before index of repeating char as in future there will be repeating char of stored index. This helps in avoiding range of chars to check again. Put in other way, we are remembering that this is max length till repeating char is encountered, if it happens we can start from that index.\n\nAlso, dictionary addition and contains is O(1).\n\n``` Csharp\npublic static int LengthOfLongestSubstring(string s)\n{\n Dictionary<char, int> letters = new Dictionary<char, int>();\n int length = 0;\n for (int i = 0; i < s.Length; i++)\n {\n if (letters.TryGetValue(s[i], out int index))\n {\n length = Math.Max(length, letters.Count);\n i = index;\n letters.Clear();\n }\n else\n {\n letters.Add(s[i], i);\n }\n }\n length = Math.Max(length, letters.Count);\n return length;\n}\n``` | 14 | 2 | [] | 3 |
longest-substring-without-repeating-characters | Java solution WITHOUT hashmap | java-solution-without-hashmap-by-gavinli-wip1 | The idea is pretty simple. We iterate thru the list once and we keep a pointer of where the current longest possible substring starts. During the iteration, we | gavinlinasd | NORMAL | 2015-09-10T08:33:24+00:00 | 2015-09-10T08:33:24+00:00 | 3,553 | false | The idea is pretty simple. We iterate thru the list once and we keep a pointer of where the current longest possible substring starts. During the iteration, we check if this last character is contained in the current substring. If so, move the ptr to the first index of the char at the string +1. Everytime we will compare and keep the max value up to date.\n\nI am calling the indexOf() method for strings which can theoretically be O(N). I am guessing this is cheaper than creating a hashmap for this set of test cases? Anyway, I just want to share my alternative solution:\n\n public class Solution {\n public int lengthOfLongestSubstring(String s) {\n if (s.length() <= 1) return s.length();\n \n int max = 1;\n int ptr = 0;\n for (int i = 1; i< s.length(); i++) {\n // find the first occurence of the char after index ptr\n int index = s.indexOf(s.charAt(i), ptr); \n if (index < i) { // it means that it is contained in s.substring(ptr, i)\n ptr = index + 1;\n }\n max = Math.max(max, i - ptr + 1);\n }\n \n return max;\n }\n } | 14 | 0 | ['Java'] | 3 |
longest-substring-without-repeating-characters | C Implementation | c-implementation-by-prabhatravi-xd1x | Approach\n Describe your approach to solving the problem. \nWe initialize an array charIndexMap to store the most recent index of each character encountered. We | prabhatravi | NORMAL | 2024-04-24T07:47:55.288700+00:00 | 2024-04-24T07:47:55.288721+00:00 | 1,973 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nWe initialize an array charIndexMap to store the most recent index of each character encountered. We use a size of 256 assuming ASCII characters and initialize all elements to -1.\nWe iterate through the characters of the input string s.\nIf a character is already in the charIndexMap and its index is greater than or equal to the startIndex, we update the startIndex to the index after the last occurrence of the character.\nWe update the index of the current character in the charIndexMap.\nWe update maxLength if the length of the current substring is longer than the previous longest substring.\nFinally, we return maxLength as the result.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$ \n\n# Code\n```\nint lengthOfLongestSubstring(char* s) {\n if (!s || !*s) // Check if the string is empty\n return 0;\n \n int charIndexMap[256]; // Assuming ASCII characters\n memset(charIndexMap, -1, sizeof(charIndexMap)); // Initialize array with -1\n \n int maxLength = 0;\n int startIndex = 0;\n int i;\n \n for (i = 0; s[i] != \'\\0\'; i++) {\n // If the character is already in the map and its index is after the start index of the current substring,\n // update the start index to the index after the last occurrence of the character\n if (charIndexMap[s[i]] != -1 && charIndexMap[s[i]] >= startIndex) {\n startIndex = charIndexMap[s[i]] + 1;\n }\n \n // Update the index of the current character\n charIndexMap[s[i]] = i;\n \n // Update the maximum length if the current substring is longer\n if (i - startIndex + 1 > maxLength) {\n maxLength = i - startIndex + 1;\n }\n }\n \n return maxLength;\n}\n``` | 13 | 0 | ['C'] | 0 |
longest-substring-without-repeating-characters | ✅Short || C++ || Java || PYTHON || JS || Explained Solution✔️ || Beginner Friendly ||🔥 | short-c-java-python-js-explained-solutio-k8om | read full article https://www.nileshblog.tech/longest-substring-without-repeating-characters/\n\nIntuition\nApproach\n1 window\n2 hashmap\n3 Two Pointer\n\nComp | amoddeshmukh844 | NORMAL | 2023-09-20T18:39:41.737413+00:00 | 2023-09-20T18:39:41.737438+00:00 | 2,981 | false | read full article https://www.nileshblog.tech/longest-substring-without-repeating-characters/\n\nIntuition\nApproach\n1 window\n2 hashmap\n3 Two Pointer\n\nComplexity\nO(n) and the space complexity is O(min(n, m))\n\nCode\nhttps://bit.ly/3iIALEY\n\n\n | 13 | 0 | ['Java'] | 0 |
count-number-of-maximum-bitwise-or-subsets | [Java/C++/Python] DP solution | javacpython-dp-solution-by-lee215-hqdb | Intuition\nSimilar to knapsack problem,\nbut use bitwise-or sum instead of math sum.\n\n# Explanation\ndp[sum] means the number of subsets with bitwise-or sum.\ | lee215 | NORMAL | 2021-10-17T04:17:50.894701+00:00 | 2021-10-18T06:35:29.343397+00:00 | 11,971 | false | # **Intuition**\nSimilar to knapsack problem,\nbut use bitwise-or sum instead of math sum.\n\n# **Explanation**\n`dp[sum]` means the number of subsets with bitwise-or `sum`.\n<br>\n\n# **Complexity**\nTime `O(mn)`, where `m = max(A)`\nSpace `O(m)`\n<br>\n\n**Java**\n```java\n public int countMaxOrSubsets(int[] A) {\n int max = 0, dp[] = new int[1 << 17];\n dp[0] = 1;\n for (int a : A) {\n for (int i = max; i >= 0; --i)\n dp[i | a] += dp[i];\n max |= a;\n }\n return dp[max];\n }\n```\n\n**C++**\n```cpp\n int countMaxOrSubsets(vector<int>& A) {\n int max = 0, dp[1 << 17] = {1};\n for (int a: A) {\n for (int i = max; i >= 0; --i)\n dp[i | a] += dp[i];\n max |= a;\n }\n return dp[max];\n }\n```\n\n**Python**\n```py\n def countMaxOrSubsets(self, A):\n dp = collections.Counter([0])\n for a in A:\n for k, v in dp.items():\n dp[k | a] += v\n return dp[max(dp)]\n```\n | 146 | 9 | [] | 27 |
count-number-of-maximum-bitwise-or-subsets | 🌟 Beats 96.00% 👏 || Step-by-Step Breakdown 💯🔥 | beats-9600-step-by-step-breakdown-by-wit-ehpy | \n\n## \uD83C\uDF1F Access Daily LeetCode Solutions Repo : click here\n\n---\n\n\n\n---\n\n# Intuition\nWhen we are asked to compute the maximum bitwise OR of s | withaarzoo | NORMAL | 2024-10-18T00:11:56.587131+00:00 | 2024-10-18T00:11:56.587161+00:00 | 25,790 | false | \n\n## **\uD83C\uDF1F Access Daily LeetCode Solutions Repo :** [click here](https://github.com/withaarzoo/LeetCode-Solutions)\n\n---\n\n\n\n---\n\n# Intuition\nWhen we are asked to compute the maximum bitwise OR of subsets and count how many subsets achieve this maximum, the problem essentially boils down to finding the largest possible OR value. Since OR operations are cumulative (meaning that once a bit is set, it stays set), the more elements we include in a subset, the closer we get to the maximum possible OR. Therefore, our goal is to:\n1. Compute the maximum OR by combining all the elements in the array.\n2. Use a method to explore every subset of the array and count how many subsets give this maximum OR value.\n\nThe key insight is that the more elements we OR together, the higher the result tends to be, making backtracking a natural choice to systematically explore each subset.\n\n---\n\n# Approach\n1. **Compute Maximum OR**: First, find the maximum OR by combining all elements using the `|` (bitwise OR) operation. This is the maximum OR that any subset can achieve.\n2. **Backtracking**: Next, use backtracking to explore all possible subsets. For each subset, compute its OR value. If the OR matches the maximum OR, increment the count.\n3. **Base Case**: If a subset OR matches the maximum, count it. Recursively explore further subsets until all have been considered.\n\n---\n\n# Complexity\n- **Time complexity**: \n The total number of subsets is \\(2^n\\), where \\(n\\) is the length of the array. For each subset, we compute the OR, which takes \\(O(n)\\). Thus, the time complexity is approximately \\(O(n \\times 2^n)\\).\n\n- **Space complexity**: \n The space complexity is \\(O(n)\\), which accounts for the recursion stack during backtracking.\n\n---\n\n# Code\n```C++ []\nclass Solution\n{\npublic:\n void backtrack(const vector<int> &nums, int index, int currentOR, int maxOR, int &count)\n {\n if (currentOR == maxOR)\n {\n count++;\n }\n\n for (int i = index; i < nums.size(); ++i)\n {\n backtrack(nums, i + 1, currentOR | nums[i], maxOR, count);\n }\n }\n\n int countMaxOrSubsets(vector<int> &nums)\n {\n int maxOR = 0;\n\n // Step 1: Compute the maximum OR\n for (int num : nums)\n {\n maxOR |= num;\n }\n\n int count = 0;\n // Step 2: Backtrack to count the subsets\n backtrack(nums, 0, 0, maxOR, count);\n\n return count;\n }\n};\n\n```\n```Java []\nclass Solution {\n public void backtrack(int[] nums, int index, int currentOR, int maxOR, int[] count) {\n if (currentOR == maxOR) {\n count[0]++;\n }\n\n for (int i = index; i < nums.length; i++) {\n backtrack(nums, i + 1, currentOR | nums[i], maxOR, count);\n }\n }\n\n public int countMaxOrSubsets(int[] nums) {\n int maxOR = 0;\n\n // Step 1: Compute the maximum OR\n for (int num : nums) {\n maxOR |= num;\n }\n\n int[] count = new int[1];\n // Step 2: Backtrack to count the subsets\n backtrack(nums, 0, 0, maxOR, count);\n\n return count[0];\n }\n}\n\n```\n```JavaScript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar countMaxOrSubsets = function (nums) {\n let maxOR = 0;\n\n // Step 1: Compute the maximum OR\n for (let num of nums) {\n maxOR |= num;\n }\n\n let count = 0;\n\n const backtrack = (index, currentOR) => {\n if (currentOR === maxOR) {\n count++;\n }\n\n for (let i = index; i < nums.length; i++) {\n backtrack(i + 1, currentOR | nums[i]);\n }\n };\n\n // Step 2: Backtrack to count the subsets\n backtrack(0, 0);\n\n return count;\n};\n\n```\n```Python []\nclass Solution:\n def backtrack(self, nums, index, currentOR, maxOR, count):\n if currentOR == maxOR:\n count[0] += 1\n \n for i in range(index, len(nums)):\n self.backtrack(nums, i + 1, currentOR | nums[i], maxOR, count)\n \n def countMaxOrSubsets(self, nums: List[int]) -> int:\n maxOR = 0\n \n # Step 1: Compute the maximum OR\n for num in nums:\n maxOR |= num\n \n count = [0]\n # Step 2: Backtrack to count the subsets\n self.backtrack(nums, 0, 0, maxOR, count)\n \n return count[0]\n\n```\n```Go []\nfunc backtrack(nums []int, index int, currentOR int, maxOR int, count *int) {\n if currentOR == maxOR {\n *count++\n }\n \n for i := index; i < len(nums); i++ {\n backtrack(nums, i+1, currentOR|nums[i], maxOR, count)\n }\n}\n\nfunc countMaxOrSubsets(nums []int) int {\n maxOR := 0\n \n // Step 1: Compute the maximum OR\n for _, num := range nums {\n maxOR |= num\n }\n \n count := 0\n // Step 2: Backtrack to count the subsets\n backtrack(nums, 0, 0, maxOR, &count)\n \n return count\n}\n\n```\n\n---\n\n# Step-by-Step Detailed Explanation\n\n1. **Initialization**:\n - We first initialize the `maxOR` variable to store the bitwise OR of all elements in the array. This represents the highest OR value a subset can achieve.\n \n2. **Backtracking Setup**:\n - We define a helper function `backtrack` that takes the current subset\'s OR value, the index to consider next, and updates the count when a subset achieves the `maxOR`.\n\n3. **Base Case**:\n - Every time the current subset\'s OR equals `maxOR`, we increment the count because this subset is one of the valid subsets.\n\n4. **Recursive Step**:\n - For each element in the array, we explore two options: either include the current element (update the OR) or skip it. This generates all possible subsets.\n\n5. **Count Result**:\n - Once all subsets have been explored through backtracking, the count gives the number of subsets whose OR matches the maximum OR.\n\n---\n\n\n | 86 | 1 | ['Array', 'Backtracking', 'Bit Manipulation', 'Enumeration', 'Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript'] | 17 |
count-number-of-maximum-bitwise-or-subsets | C++ Bitmask + DP | c-bitmask-dp-by-lzl124631x-t10z | See my latest update in repo LeetCode\n\n## Solution 1. Bitmask\n\n1. Compute goal which is the maximum possible bitwise OR of a subset of nums, i.e. the bitwis | lzl124631x | NORMAL | 2021-10-17T04:03:31.982005+00:00 | 2021-10-17T05:13:29.701020+00:00 | 5,282 | false | See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1. Bitmask\n\n1. Compute `goal` which is the maximum possible bitwise OR of a subset of `nums`, i.e. the bitwise OR of all the numbers in `nums`. \n2. Enumerate all non-empty subsets of `nums` using bitmask and compute the bitwise OR of each of them. Increment answer if the subset\'s bitwise OR is the same as `goal`.\n\n```cpp\n// OJ: https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/\n// Author: github.com/lzl124631x\n// Time: O(2^N * N)\n// Space: O(1)\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& A) {\n int goal = 0, N = A.size(), ans = 0;\n for (int n : A) goal |= n;\n for (int m = 1; m < 1 << N; ++m) {\n int x = 0;\n for (int i = 0; i < N; ++i) {\n if (m >> i & 1) x |= A[i];\n }\n if (x == goal) ++ans;\n }\n return ans;\n }\n};\n```\n\nWe can use DP to reduce the time complexity at the cost of space complexity\n\n```cpp\n// OJ: https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/\n// Author: github.com/lzl124631x\n// Time: O(2^N)\n// Space: O(2^N)\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& A) {\n int goal = 0, N = A.size(), ans = 0;\n vector<int> dp(1 << N);\n for (int n : A) goal |= n;\n for (int m = 1; m < 1 << N; ++m) {\n int lowbit = m & -m;\n dp[m] = dp[m - lowbit] | A[__builtin_ctz(lowbit)];\n if (dp[m] == goal) ++ans;\n }\n return ans;\n }\n};\n``` | 43 | 4 | [] | 6 |
count-number-of-maximum-bitwise-or-subsets | Recursion via take or skip with/without Memo vs BitMask||Beats 100% | recursion-via-take-or-skip-withwithout-m-6vfh | Intuition\n Describe your first thoughts on how to solve this problem. \nIf you look at the constraints carefully, this computational $O(2^n)$ solution is in f | anwendeng | NORMAL | 2024-10-18T00:31:55.349954+00:00 | 2024-10-18T02:44:08.935249+00:00 | 5,817 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf you look at the constraints carefully, this computational $O(2^n)$ solution is in fact not slower than other possible solutions, since `1<=n<=16`.\n\nRecursion with/without memo can be solved with the argument take or skip; this recursion solution is in fact brute force which is faster than the recursive DP. Thanks to @stephen_byerley, applying his suggestion to add an early stop in the recursion solution which run 0ms & beats 100%\n\nAn iterative version with bit mask is also done which uses the same method to solve Leetcode 78 Subsets.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Compute `max_OR` by using `accumulate` with operation `bit_or<>()`\n2. define the recursion `int f(int i, unsigned acc_or, vector<int>& nums)` by using take or skip argument. An improved version is implemented by adding an early stop ` if (acc_or==max_OR) return 1<<(i+1);` since there are $2^{i+1}$ subsets containing this current subset.( thanks to @stephen_byerley)\n3. `f(n-1, 0, nums)` is the answer\n4. The recursion+memo is using same argument applied in the 1st C++ code.\n5. Since `1 <= nums[i] <= 10^5`, the $O(n* max\\_OR)$TC solution is even much slower\n6. An iterative bit mask method is also provided.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nRecursion( brute force) :$O(2^n)$\nRecursion with memo:$O(n* max\\_OR)$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(n)$ vs $O(n* max\\_OR)$\n# Code||C++ Recursion w/o Memo 6ms Beats 97.88%|| improved version 0ms beats 100%\n```cpp []\nclass Solution {\npublic:\n int n;\n unsigned max_OR;\n int f(int i, unsigned acc_or, vector<int>& nums){\n if (i<0) return (acc_or==max_OR)?1:0;\n int skip=f(i-1, acc_or, nums);\n int take=f(i-1, acc_or| nums[i], nums);\n return skip+take;\n }\n int countMaxOrSubsets(vector<int>& nums) {\n n=nums.size();\n max_OR=accumulate(nums.begin(), nums.end(), 0, bit_or<>());\n return f(n-1, 0, nums);\n }\n};\n\n\nauto init = []() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n```improved []\nclass Solution {\npublic:\n int n;\n unsigned max_OR;\n int f(int i, unsigned acc_or, vector<int>& nums){\n if (i<0) return (acc_or==max_OR)?1:0;\n if (acc_or==max_OR) return 1<<(i+1);// early stop\n int skip=f(i-1, acc_or, nums);\n int take=f(i-1, acc_or| nums[i], nums);\n return skip+take;\n }\n int countMaxOrSubsets(vector<int>& nums) {\n n=nums.size();\n max_OR=accumulate(nums.begin(), nums.end(), 0, bit_or<>());\n return f(n-1, 0, nums);\n }\n};\n\n\nauto init = []() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# C++ recursion+memo ||27ms Beats 48.56%\n```\nclass Solution {\npublic:\n int n;\n unsigned max_OR;\n vector<vector<int>> dp; // (i, acc_or)\n int f(int i, unsigned acc_or, vector<int>& nums){\n if (i<0) return (acc_or==max_OR)?1:0;\n if (dp[i][acc_or]!=-1) return dp[i][acc_or];\n int skip=f(i-1, acc_or, nums);\n int take=f(i-1, acc_or| nums[i], nums);\n return dp[i][acc_or]=skip+take;\n }\n int countMaxOrSubsets(vector<int>& nums) {\n n=nums.size();\n max_OR=accumulate(nums.begin(), nums.end(), 0, bit_or<>());\n dp.assign(n, vector<int>(max_OR+1, -1));\n return f(n-1, 0, nums);\n }\n};\n\n\nauto init = []() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# Iterative Version Using bit mask method\n\nUsing the method solving [78. Subsets](https://leetcode.com/problems/subsets/solutions/5186389/bit-mask-backtracking-0ms-beats-100/)\n\n[Please turn on English subtitles if neccesary]\n[https://youtu.be/LzUR3Ul2Qjg?si=Scs98kfTqAENzsle](https://youtu.be/LzUR3Ul2Qjg?si=Scs98kfTqAENzsle)\n\n# Code using bitmask\n```\nclass Solution {\npublic:\n static int countMaxOrSubsets(vector<int>& nums) {\n const unsigned n=nums.size(), bmask=(1<<n)-1;\n int cnt=0, max_OR;\n for (int mask=1; mask<=bmask; mask++){\n unsigned acc_or=0;\n for(int i=0; i<n; i++){\n if ( (mask>>i)& 1) acc_or|=nums[i];\n }\n if (acc_or>max_OR) max_OR=acc_or, cnt=1;\n else if (acc_or==max_OR) cnt++;\n }\n return cnt;\n }\n};\n```\n | 29 | 0 | ['Dynamic Programming', 'Bit Manipulation', 'Recursion', 'Memoization', 'C++'] | 10 |
count-number-of-maximum-bitwise-or-subsets | Java beats 100% | java-beats-100-by-noahjpark-u0sp | Intuition: Accumulate the maximum bitwise value from the array then apply the subset formula to accumulate all subsets that have that value.\n\n```\nclass Solut | noahjpark | NORMAL | 2021-10-17T04:03:20.382968+00:00 | 2021-10-17T04:03:20.382990+00:00 | 2,113 | false | Intuition: Accumulate the maximum bitwise value from the array then apply the subset formula to accumulate all subsets that have that value.\n\n```\nclass Solution {\n \n int res = 0, target = 0;\n \n public int countMaxOrSubsets(int[] nums) {\n for (int num : nums)\n target |= num;\n \n dfs(nums, 0, 0);\n return res;\n }\n \n public void dfs(int[] nums, int idx, int mask) {\n if (mask == target) res++;\n \n for (int i = idx; i < nums.length; i++)\n dfs(nums, i + 1, mask | nums[i]);\n }\n \n} | 28 | 2 | [] | 2 |
count-number-of-maximum-bitwise-or-subsets | Python | Backtracking Pattern | python-backtracking-pattern-by-khosiyat-66l8 | see the Successfully Accepted Submission\n\n# Code\npython3 []\nfrom typing import List\n\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> | Khosiyat | NORMAL | 2024-10-18T02:18:27.383555+00:00 | 2024-10-18T02:18:27.383590+00:00 | 1,983 | false | [see the Successfully Accepted Submission](https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/submissions/1425960007/?envType=daily-question&envId=2024-10-18)\n\n# Code\n```python3 []\nfrom typing import List\n\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n # Step 1: Find the maximum possible bitwise OR of the entire array\n max_or = 0\n for num in nums:\n max_or |= num\n \n # Step 2: Helper function to recursively explore subsets and count those with max OR\n def backtrack(index, current_or):\n if index == len(nums):\n return 1 if current_or == max_or else 0\n # Case 1: Include the current element in the subset\n include = backtrack(index + 1, current_or | nums[index])\n # Case 2: Exclude the current element from the subset\n exclude = backtrack(index + 1, current_or)\n return include + exclude\n \n # Step 3: Start backtracking from index 0 and initial OR value 0\n return backtrack(0, 0)\n\n```\n\n# Approach:\n\n## 1. Calculate Maximum Bitwise OR:\nFirst, calculate the maximum possible bitwise OR of all subsets. The overall OR can be computed by doing a bitwise OR of all elements of the array. This will give us the maximum OR that we want to achieve from some subset.\n\n## 2. Generate All Subsets:\nWe can use a backtracking approach or bit manipulation to generate all possible subsets. Given that the array length is at most 16, the number of subsets is at most \\(2^{16} = 65536\\), which is feasible for brute-force generation.\n\n## 3. Count Subsets with Maximum OR:\nAs we generate each subset, compute its OR and compare it with the maximum OR value. If it matches the maximum OR, increment the count.\n\n# Algorithm:\n1. Compute the maximum OR by taking the OR of all elements.\n2. Initialize a counter for subsets with the maximum OR.\n3. Use backtracking or bit manipulation to generate all subsets.\n4. For each subset, compute its OR.\n5. If the OR of the subset equals the maximum OR, increase the count.\n6. Return the final count.\n\n# Explanation of the Code:\n- **Step 1**: We compute the `max_or` by taking the OR of all elements in the array. This gives us the maximum OR we need to compare against.\n- **Step 2**: The `backtrack` function is used to recursively explore all subsets:\n - It has two choices at each index: include the current element in the subset or exclude it.\n - If the current OR value of a subset equals `max_or` and we have reached the end of the array (`index == len(nums)`), we count this subset.\n- **Step 3**: We call `backtrack` starting from index `0` and with an initial OR value of `0`.\n\n# Time Complexity:\nThe time complexity of this approach is \\(O(2^n)\\), where \\(n\\) is the number of elements in `nums`. Since \\(n\\) is at most 16, this is manageable within the given constraints.\n\n# Example Walkthrough:\n- **Example 1**: \nFor `nums = [3, 1]`, the maximum OR is `3` (since `3 | 1 = 3`). \n - The subsets that yield this OR are `[3]` and `[3, 1]`, so the result is `2`.\n \n- **Example 2**: \nFor `nums = [3, 2, 1, 5]`, the maximum OR is `7` (since `3 | 2 | 1 | 5 = 7`). \n - The subsets that yield this OR are `[3, 5]`, `[3, 1, 5]`, `[3, 2, 5]`, `[3, 2, 1, 5]`, `[2, 5]`, and `[2, 1, 5]`, so the result is `6`.\n\n\n | 21 | 0 | ['Python3'] | 4 |
count-number-of-maximum-bitwise-or-subsets | Java | (Subset Problem) | beats 100% | java-subset-problem-beats-100-by-smanett-tnfh | \nclass Solution {\n public int countMaxOrSubsets(int[] nums) {\n \n subsets(nums, 0, 0);\n return count;\n }\n \n int count = | smanettone | NORMAL | 2021-10-17T04:03:31.206381+00:00 | 2021-10-17T07:15:45.484859+00:00 | 2,088 | false | ```\nclass Solution {\n public int countMaxOrSubsets(int[] nums) {\n \n subsets(nums, 0, 0);\n return count;\n }\n \n int count = 0;\n int maxOR = 0;\n \n private void subsets(int[] arr, int vidx, int OR){\n \n if(vidx == arr.length){\n \n if(OR == maxOR){\n count ++;\n }else if(OR > maxOR){\n count = 1;\n maxOR = OR;\n }\n \n return;\n }\n \n // include\n subsets(arr, vidx+1, OR | arr[vidx]);\n \n // exclude\n subsets(arr, vidx+1, OR);\n }\n}\n``` | 19 | 1 | ['Bitmask', 'Java'] | 1 |
count-number-of-maximum-bitwise-or-subsets | Simple recursive solution | simple-recursive-solution-by-ayashi-5lm9 | Maximum Bitwise-OR is possible when we take bitwise-or of all the numbers.\n\nStep 1: Calculate the bitwise of all the numbers.\nStep 2: Find all bitwise of all | ayashi | NORMAL | 2021-10-17T04:03:07.128382+00:00 | 2021-10-17T04:04:22.023196+00:00 | 2,464 | false | **Maximum Bitwise-OR** is possible when we take **bitwise-or of all the numbers.**\n\nStep 1: Calculate the bitwise of all the numbers.\nStep 2: Find all bitwise of all the possible subsets recursively.\nStep 3: Simply compare the values of step 2 with step 1\n\n\'\'\'\nclass Solution {\npublic:\n \n int subset(vector<int> &nums, int i, int a,int b)\n {\n int ans =0;\n if(i<0)\n return 0;\n if(a == (b|nums[i]))\n ans =1;\n return ans + subset(nums,i-1,a,b) + subset(nums,i-1,a,b|nums[i]);\n }\n \n int countMaxOrSubsets(vector<int>& nums) {\n \n int a=0;\n \n for(auto i:nums)\n {\n a = a|i;\n }\n \n int ans = subset(nums,nums.size()-1,a,0);\n \n return ans ;\n \n }\n};\n\'\'\' | 14 | 2 | ['Recursion', 'C'] | 2 |
count-number-of-maximum-bitwise-or-subsets | The actual optimal solution. O(n*maxOR) time, O(1) space | the-actual-optimal-solution-onmaxor-time-xw8d | Approach\nFind the maximum OR value, then efficiently count the number of subsets of the array that do not have the maximum OR value using inclusion-exclusion.\ | TheodoreGossett | NORMAL | 2024-10-18T00:47:56.040682+00:00 | 2024-10-18T08:02:16.992094+00:00 | 2,008 | false | # Approach\nFind the maximum OR value, then efficiently count the number of subsets of the array that do not have the maximum OR value using inclusion-exclusion.\n\nHere is a good resource to learn about the principle of inclusion-exclusion: https://artofproblemsolving.com/wiki/index.php/Principle_of_Inclusion-Exclusion\n\n# Complexity\n- Time complexity:\nO(NM), where M is the max or value, and N is the size of nums.\n\n- Space complexity:\nO(1), unlike the dp solution.\n\n# Code\n```cpp []\n#pragma GCC target("popcnt")\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) { //O(n*maxValue) time, O(1) storage\n int maxOr=0; \n for(int n:nums) maxOr|=n;\n int numberOfBadSubsets = 0; //bad subset means subset whose OR is less than maxOR\n for(int mask=maxOr;mask; mask=(mask-1)&maxOr){ //iterates over subsets of the set bits of the maxOr\n int cnt = 0; \n for(int n:nums) if(!(n&mask)) cnt++; //counts elements of nums that have all 0s in the positions that are 1s in the current mask\n numberOfBadSubsets += (__builtin_popcount(mask)%2 ? 1 : -1)*((1<<cnt)-1); //inclusion exclusion\n }\n return (1<<nums.size())-1- numberOfBadSubsets;//total number of subsets minus number of bad subsets\n }\n};\n``` | 13 | 0 | ['C++'] | 6 |
count-number-of-maximum-bitwise-or-subsets | C++ | Beginner friendly | Bitmask | Checking all subsets | c-beginner-friendly-bitmask-checking-all-9s0j | Feel free to comment \n\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n \n int i,j,max_possible_or=0,n=nums.size(),an | emiya100 | NORMAL | 2021-10-17T04:02:34.641618+00:00 | 2021-10-17T04:07:33.562077+00:00 | 1,304 | false | Feel free to comment \n```\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n \n int i,j,max_possible_or=0,n=nums.size(),ans=0;\n \n //maximum possible or=or of all number in array\n for(i=0;i<n;i++)\n {\n max_possible_or=nums[i]|max_possible_or;\n }\n \n //checking all subset \n \n \n for(i=1;i<(1<<n);i++)\n {\n int p=0;\n for(j=0;j<n;j++)\n {\n if(i&(1<<j))\n {\n p=p|nums[j];\n }\n }\n //if xor of given subset is equal to maximum possible or\n\t\t\t\n if(p==max_possible_or)\n {\n ans++;\n }\n }\n \n return ans;\n \n }\n};\n``` | 12 | 0 | ['C', 'C++'] | 2 |
count-number-of-maximum-bitwise-or-subsets | [Python3] top-down dp | python3-top-down-dp-by-ye15-753w | \n\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n target = reduce(or_, nums)\n \n @cache\n def fn(i, m | ye15 | NORMAL | 2021-10-17T04:04:16.003691+00:00 | 2021-10-17T04:04:16.003738+00:00 | 1,860 | false | \n```\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n target = reduce(or_, nums)\n \n @cache\n def fn(i, mask): \n """Return number of subsets to get target."""\n if mask == target: return 2**(len(nums)-i)\n if i == len(nums): return 0 \n return fn(i+1, mask | nums[i]) + fn(i+1, mask)\n \n return fn(0, 0)\n``` | 11 | 0 | ['Python3'] | 2 |
count-number-of-maximum-bitwise-or-subsets | C++ || Easy Pick/Not Pick pattern✅✅✅ | c-easy-picknot-pick-pattern-by-arunk_lee-t5ck | Intuition\nThe problem involves finding the number of subsets in which the bitwise OR of all elements equals the maximum possible OR of the entire array. The fi | arunk_leetcode | NORMAL | 2024-10-18T05:01:54.675315+00:00 | 2024-10-18T05:01:54.675342+00:00 | 2,936 | false | # Intuition\nThe problem involves finding the number of subsets in which the bitwise OR of all elements equals the maximum possible OR of the entire array. The first intuition is to generate all subsets and compute their OR values, then compare each subset\'s OR value with the maximum OR that can be achieved by considering all elements in the array.\n\n# Approach\n1. **Maximum OR Calculation**: First, compute the maximum possible OR (`maxi`) of all elements in the array.\n2. **Recursion**: Use recursion to explore all subsets. For each element, we either include it in the current subset OR or exclude it.\n3. **Subset OR Comparison**: Once all elements have been processed, check if the OR of the current subset equals the maximum OR (`maxi`).\n4. **Counting Valid Subsets**: Count the number of valid subsets where the subset OR equals the maximum OR.\n\n# Complexity\n- **Time complexity**: \n The time complexity is $$O(2^n)$$ because we explore all subsets, and there are $$2^n$$ subsets for an array of size `n`.\n\n- **Space complexity**: \n The space complexity is $$O(n)$$ due to the recursive call stack, where `n` is the size of the input array `nums`.\n\n# Code\n```cpp\nclass Solution {\npublic:\n // Recursive function to explore subsets and count those with maximum OR value\n int solve(int i, int ors, int maxi, vector<int>& nums) {\n if(i >= nums.size()){\n // Base case: if OR of the current subset equals the maximum OR, count it\n return (ors == maxi) ? 1 : 0;\n }\n\n // Include the current element in the subset OR\n int cnt = 0;\n cnt += solve(i + 1, ors | nums[i], maxi, nums);\n \n // Exclude the current element from the subset OR\n cnt += solve(i + 1, ors, maxi, nums);\n \n return cnt;\n }\n\n // Function to count the number of subsets with maximum OR value\n int countMaxOrSubsets(vector<int>& nums) {\n int maxi = 0;\n \n // Calculate the maximum OR value from all elements\n for(auto it: nums){\n maxi |= it;\n }\n\n // Start recursion from the first element with OR = 0\n return solve(0, 0, maxi, nums);\n }\n};\n | 10 | 0 | ['Dynamic Programming', 'Recursion', 'C++'] | 6 |
count-number-of-maximum-bitwise-or-subsets | Optimized C++ Approach with Explanation | optimized-c-approach-with-explanation-by-3dbh | Intuition\n Describe your first thoughts on how to solve this problem. \nThe bitwise OR operation\'s result always has ith bit set, whenever any one of the bits | Ankit_Rupal | NORMAL | 2022-10-09T11:39:20.146779+00:00 | 2023-01-03T19:53:56.692693+00:00 | 639 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe bitwise OR operation\'s result always has ith bit set, whenever any one of the bits is set. Thus, the maximum possible value of the bitwise OR of any subset of array a is the bitwise OR of array a itself!\nNow the question boils down to the simpler question of \n"Given a target t, find the number of subsets in array a whose bitwise OR is equal to t."\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo find the number of subsets, we can simply follow a two step approach.\n1. Find the maximum bitwise OR of the array by simply traversing through the array and taking bitwise OR of every element. Store the result in target variable.\n2. Now we use a Backtracking approach of finding the number of subsets by following the principle of **"Take and Not Take"**.\n\n##### RECURSIVE FORMULATION:\n **DEFINITION :** The function **f(idx, target)** denotes the count of **subsets ranging from index i to n-1** having bitwise OR equal to target\n1. **Take** : f(idx+1,(curr | nums[idx]));\n2. **Not Take** : f(idx+1,curr);\n\nWe have to take every possible subset into our consideration, therefore,\n`return f(idx + 1,(curr | nums[idx])) + f(idx + 1,curr));`\n\n##### BASE CASE:\nWe only have a single base case wherein, if we ever reach out of bound i.e., idx == n, then we are simply going to check one thing.\n> if(curr == target) return 1;\n> else return 0;\n\nAlthough not in code, but we can simplify the code even further by replacing with a single line:\n> return (target == curr);\n\nHowever, i am suspicious that replacing it might end up using some extra time but anyway :-)\n\n# Complexity\n- Time complexity: $$O(2^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\n\n# EXPLANATION FOR TIME AND SPACE COMPLEXITY\n\n> **TIME COMPLEXITY** : At every index, we have two options, either to take it or not take it. Overall we have n indices (ranging from 0 to n-1), so the overall time taken would be [2 * 2 * ....... * 2] (for n times) => $$O(2^n)$$ \n\n\n> **SPACE COMPLEXITY** : We are not using any extra space, just few variables and further more we have passed almost everything by reference (even target variable). The only thing left is the internal memory used in Stack Space of Recursion. Thus, linear space complexity!\n# Code\n```\nclass Solution {\npublic:\n int countSubsetsTarget(int idx,int curr,int const &target,vector<int> const &nums){\n if(idx == nums.size()){\n if(target == curr)\n return 1;\n return 0;\n }\n return (countSubsetsTarget(idx+1,(curr | nums[idx]),target,nums) + countSubsetsTarget(idx+1,curr,target,nums));\n }\n\n int countMaxOrSubsets(vector<int>& nums) {\n int target = 0;\n for(auto &x:nums)\n target |= x;\n return countSubsetsTarget(0,0,target,nums);\n }\n};\n```\n\n**Please Upvote if you liked it!** | 10 | 0 | ['Backtracking', 'C++'] | 0 |
count-number-of-maximum-bitwise-or-subsets | ✅ One Line Solution | one-line-solution-by-mikposp-o80x | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1.1 - Recursive\nTime complexity: O(2^n) | MikPosp | NORMAL | 2024-10-18T09:16:40.508299+00:00 | 2024-10-18T11:16:35.710569+00:00 | 613 | false | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1.1 - Recursive\nTime complexity: $$O(2^n)$$. Space complexity: $$O(n)$$.\n```python3\nclass Solution:\n def countMaxOrSubsets(self, a: List[int]) -> int:\n return (f:=lambda i,o,O=reduce(or_,a):a[i:] and f(i+1,o)+f(i+1,o|a[i]) or o==O)(0,0)\n```\n\n# Code #1.2 - Unwrapped\n```python3\nclass Solution:\n def countMaxOrSubsets(self, a: List[int]) -> int:\n O = reduce(or_, a) # Max OR\n\n def f(i, o):\n if i < len(a):\n return f(i+1, o) + f(i+1, o|a[i])\n \n return o == O\n\n return f(0, 0)\n```\n\n# Code #1.3 - Cached Recursive - Fastest!\nTime complexity: $$O(n*maxOr)$$. Space complexity: $$O(n*maxOr)$$.\n```python3\nclass Solution:\n def countMaxOrSubsets(self, a: List[int]) -> int:\n return (f:=cache(lambda i,o,O=reduce(or_,a):a[i:] and f(i+1,o)+f(i+1,o|a[i]) or o==O))(0,0)\n```\n\n# Code #2 - Combinations\nTime complexity: $$O(2^n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def countMaxOrSubsets(self, a: List[int]) -> int:\n return sum(reduce(or_,q)==reduce(or_,a) for k in range(len(a)) for q in combinations(a,k+1))\n```\n\n# Code #3.1 - Bitmask\nTime complexity: $$O(2^n)$$. Space complexity: $$O(1)$$.\n```python3\nclass Solution:\n def countMaxOrSubsets(self, a: List[int]) -> int:\n return sum(reduce(or_,(v for i,v in enumerate(a) if 1<<i&m))==reduce(or_,a) for m in range(1,1<<len(a)))\n```\n\n# Code #3.2 - Unwrapped\n```python3\nclass Solution:\n def countMaxOrSubsets(self, a: List[int]) -> int:\n res = 0\n for m in range(1, 1<<len(a)):\n res += reduce(or_, (v for i,v in enumerate(a) if 1<<i&m)) == reduce(or_,a)\n\n return res\n```\n\n(Disclaimer 2: code above is just a product of fantasy packed into one line, it is not claimed to be \'true\' oneliners - please, remind about drawbacks only if you know how to make it better) | 9 | 0 | ['Array', 'Backtracking', 'Bit Manipulation', 'Recursion', 'Memoization', 'Combinatorics', 'Enumeration', 'Python', 'Python3'] | 1 |
count-number-of-maximum-bitwise-or-subsets | Easy C++ solution | DP | With Comments | easy-c-solution-dp-with-comments-by-iash-09gl | \nclass Solution {\npublic:\n #define maxN 17\n #define maxM (1<<17)\n\n int dp[maxN][maxM];\n bool v[maxN][maxM];\n int findCnt(vector<int> arr, | iashi_g | NORMAL | 2021-10-17T04:09:19.925681+00:00 | 2021-10-17T04:09:19.925716+00:00 | 1,605 | false | ```\nclass Solution {\npublic:\n #define maxN 17\n #define maxM (1<<17)\n\n int dp[maxN][maxM];\n bool v[maxN][maxM];\n int findCnt(vector<int> arr, int start, int curr, int n, int maxor)\n{\n // Base case\n if (start == n) {\n return (curr == maxor);\n }\n \n if (v[start][curr])\n return dp[start][curr];\n \n // Setting the state as visited\n v[start][curr] = 1;\n \n // adding the counts of including the current element and excluding the current element\n dp[start][curr]\n = findCnt(arr, start + 1, curr, n, maxor)\n + findCnt(arr, start + 1, (curr | arr[start]), n, maxor);\n \n return dp[start][curr];\n}\n \nint OR(vector<int> data){\n int n = data.size();\n int mOR = 0;\n for (int i = 0; i < n; ++i) {\n mOR |= data[i];\n }\n\n return mOR;\n}\n \n int countMaxOrSubsets(vector<int>& arr) {\n int mor = OR(arr);\n return findCnt(arr,0,0,arr.size(),mor);\n }\n};\n``` | 9 | 1 | ['Dynamic Programming', 'C'] | 3 |
count-number-of-maximum-bitwise-or-subsets | 💡 | O(2^n) | C++ 7ms| Java 8ms | Efficient Backtracking 🧠 | | o2n-c-7ms-java-8ms-efficient-backtrackin-ky0f | \n---\n\n> # Intuition\nWe need to calculate the maximum bitwise OR possible from any subset of the given numbers. Once we identify that, the task is to count h | user4612MW | NORMAL | 2024-10-18T04:02:33.044410+00:00 | 2024-10-18T04:02:33.044438+00:00 | 1,479 | false | #\n---\n\n> # Intuition\nWe need to calculate the maximum bitwise OR possible from any subset of the given numbers. Once we identify that, the task is to count how many subsets achieve this maximum. We can use a backtracking (DFS) approach to explore all subsets, keeping track of the current bitwise OR. If the OR matches the maximum value, we increment the count.\n\n> # Approach\n> **Backtracking**: Use DFS to explore all subsets. For each number, we either include it in the subset (updating the OR value) or exclude it, moving recursively to the next number.\n> **Max OR Calculation**: First, calculate the maximum possible bitwise OR for all numbers combined. Then, in each recursive call, compare the current OR value with the max OR and count how many subsets reach this maximum.\n\n> # Complexity\n- **Time Complexity**: $$O(2^n)$$, where $$n$$ is the size of the input array, as we need to check all subsets (which are $$2^n$$ in total).\n- **Space Complexity**: $$O(n)$$, for the recursion stack.\n\n---\n\n> # Code\n\n```cpp []\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int maxOr = accumulate(nums.begin(), nums.end(), 0, [](int a, int b) { return a | b; });\n return dfs(nums, 0, 0, maxOr);\n }\nprivate:\n int dfs(vector<int>& nums, int i, int orVal, int maxOr) {\n return i == nums.size() ? (orVal == maxOr) : dfs(nums, i + 1, orVal | nums[i], maxOr) + dfs(nums, i + 1, orVal, maxOr);\n }\n};\nauto io_opt = [] { ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();\n```\n```python []\nclass Solution:\n def countMaxOrSubsets(self, nums):\n max_or = reduce(lambda a, b: a | b, nums)\n return self.dfs(nums, 0, 0, max_or)\n def dfs(self, nums, i, or_val, max_or):\n return (or_val == max_or) if i == len(nums) else self.dfs(nums, i + 1, or_val | nums[i], max_or) + self.dfs(nums, i + 1, or_val, max_or)\n```\n```java []\nclass Solution {\n public int countMaxOrSubsets(int[] nums) {\n int max = 0;\n for (int n : nums) max |= n;\n return dfs(nums, 0, 0, max);\n }\n private int dfs(int[] nums, int i, int or, int max) {\n if (i == nums.length) return or == max ? 1 : 0;\n return dfs(nums, i + 1, or | nums[i], max) + dfs(nums, i + 1, or, max);\n }\n}\n```\n\n---\n\n\n---\n | 8 | 0 | ['C++', 'Java', 'Python3'] | 4 |
count-number-of-maximum-bitwise-or-subsets | 💥Runtime beats 100.00%, memory beats 94.44% [EXPLAINED] | runtime-beats-10000-memory-beats-9444-ex-0ye9 | Intuition\nFind subsets of an array that yield the highest possible bitwise OR. The bitwise OR combines bits of numbers, resulting in a number that has bits set | r9n | NORMAL | 2024-10-18T04:40:18.345346+00:00 | 2024-10-18T04:40:18.345384+00:00 | 34 | false | # Intuition\nFind subsets of an array that yield the highest possible bitwise OR. The bitwise OR combines bits of numbers, resulting in a number that has bits set to 1 wherever any of the numbers have bits set to 1. Understanding how subsets interact to achieve this maximum OR helps us count how many different combinations lead to that value.\n\n# Approach\nCalculate the maximum bitwise OR from all elements, then use a recursive function to explore subsets, counting those that achieve this maximum OR.\n\n# Complexity\n- Time complexity:\n\uD835\uDC42 ( 2 \uD835\uDC5B ) O(2 n ), where \uD835\uDC5B n is the number of elements in the array, because we potentially explore all subsets\n\n- Space complexity:\nO(n) due to the recursion stack, which can go as deep as the number of elements.\n\n# Code\n```csharp []\nclass Solution {\n // Recursive function to count subsets that yield the maximum bitwise OR\n private int CountSubsetsWithMaxXor(int[] nums, int index, int currentXor, int maxXor) {\n // Base case: if all elements have been considered\n if (index == nums.Length) {\n return currentXor == maxXor ? 1 : 0; // Return 1 if current XOR matches max\n }\n\n // Include the current element in the XOR calculation\n int includeCurrent = CountSubsetsWithMaxXor(nums, index + 1, currentXor | nums[index], maxXor);\n \n // Exclude the current element and keep current XOR unchanged\n int excludeCurrent = CountSubsetsWithMaxXor(nums, index + 1, currentXor, maxXor);\n \n // Return the total count of valid subsets\n return includeCurrent + excludeCurrent;\n }\n\n // Main function to count the number of subsets with maximum bitwise OR\n public int CountMaxOrSubsets(int[] nums) {\n int maxXor = 0;\n\n // Calculate the maximum possible bitwise OR from all elements\n foreach (int num in nums) {\n maxXor |= num;\n }\n \n // Call the recursive function starting from index 0 and initial XOR of 0\n return CountSubsetsWithMaxXor(nums, 0, 0, maxXor);\n }\n}\n\n\n``` | 6 | 0 | ['C#'] | 0 |
count-number-of-maximum-bitwise-or-subsets | Here's a simple and well- explained Dart solution of the problem. | heres-a-simple-and-well-explained-dart-s-uskb | **Bold****# 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# Complex | _abhiramks | NORMAL | 2024-10-18T04:13:50.974967+00:00 | 2024-10-18T04:13:50.974990+00:00 | 34 | false | ******Bold******# 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```dart []\nclass Solution {\n int countMaxOrSubsets(List<int> nums) {\n int maxOr = 0;\n // Step 1: Find the maximum possible OR value of all elements combined\n for (int num in nums) {\n maxOr |= num; \n }\n // Step 2: Recursive function to count subsets with max OR\n int countSubsets(int index, int currentOr) {\n if (index == nums.length) {\n return currentOr == maxOr ? 1 : 0;\n }\n // Option 1: Include current element in subset and OR it\n int include = countSubsets(index + 1, currentOr | nums[index]);\n // Option 2: Exclude current element from subset\n int exclude = countSubsets(index + 1, currentOr);\n // Return total count (including and excluding current element)\n return include + exclude;\n }\n // Step 3: Start the recursive counting from index 0 and initial OR value 0\n return countSubsets(0, 0);\n }\n}\n\n\n``` | 6 | 0 | ['Dart'] | 1 |
count-number-of-maximum-bitwise-or-subsets | ✅✅Easiest & Best Solution in C++ || O(1) SC💯✅ | easiest-best-solution-in-c-o1-sc-by-adis-0u35 | Code\n### Please Upvote if u liked my Solution\uD83E\uDD17\n\nclass Solution {\npublic:\n int count=0;\n void calculate(int ind, vector<int>& nums, int si | aDish_21 | NORMAL | 2022-10-04T10:04:51.903497+00:00 | 2023-04-10T08:16:43.927937+00:00 | 877 | false | # Code\n### Please Upvote if u liked my Solution\uD83E\uDD17\n```\nclass Solution {\npublic:\n int count=0;\n void calculate(int ind, vector<int>& nums, int size, int bitOR, int x){\n if(ind==size){\n if(x==bitOR)\n count++;\n return;\n }\n calculate(ind+1, nums, size, bitOR, x | nums[ind]);\n calculate(ind+1, nums, size, bitOR, x);\n }\n int countMaxOrSubsets(vector<int>& nums) {\n int size=nums.size(),bitOR=0;\n for(auto it:nums)\n bitOR |= it;\n calculate(0, nums, size, bitOR, 0);\n return count;\n }\n};\n``` | 6 | 0 | ['Array', 'Backtracking', 'Bit Manipulation', 'C++'] | 0 |
count-number-of-maximum-bitwise-or-subsets | JAVA Solution: well-explained. Easy to understand | java-solution-well-explained-easy-to-und-73nr | Hi there ! \nIdea of this solution could be devided on two parts \n1. Using backtracking algorithm find all possible subsets. I would highly suggest to solve 78 | sgusache | NORMAL | 2022-05-09T19:33:37.815876+00:00 | 2022-05-09T19:45:44.410247+00:00 | 675 | false | Hi there ! \nIdea of this solution could be devided on two parts \n1. Using backtracking algorithm find all possible subsets. I would highly suggest to solve [```78. Subsets``` ](https://leetcode.com/problems/subsets/)first. \n2. Use ArrayList to store current betwise OR of subset \n\n## Let\'s take a look at this example\n**Intput** : ```nums = [1,2,3]```\nThis is what subsets of nums we will calculate on iteration if we just use the backtracking part\n```[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]```\nWhat we also want is to check on each iteration if subset bitwise or is matching maximum possible bitwise-OR\n1. The maximum bitwise-OR is the bitwise-OR of the whole array. Store that value in ```max```\n2. We also want to know what is current bitwise-OR of our subset . To do that I\'m using arrayList ```curr``` Which is kind of like a mapping between subset and betwise-OR of that subset \nExample: using this ```nums = [1,2,3]``` \n```[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]``` - all possible subsets\n```[[],[1], [3], [3], [2], [3], [3]]``` - ```curr``` will look like that \n```\nclass Solution {\n int n; // length of nums\n int max; // max of betwise-OR of nums\n int result = 0; // result\n public int countMaxOrSubsets(int[] nums) {\n n = nums.length;\n max = nums[0]; \n for(int i = 1; i < nums.length; i++) //going through nums to find betwise-OR\n max = max | nums[i];\n backtrack(0,new ArrayList<>(),nums); // call magic function which go over all possible subsets of nums \n return result;\n }\n public void backtrack(int first, ArrayList<Integer> curr, int [] nums){\n if(curr.size() > 0 && curr.get(curr.size() - 1) == max) // checking if current betwise-OR equal the maximum \n result++;\n for(int i = first; i < n; i++){\n if(curr.size() > 0) \n curr.add(nums[i] | curr.get(curr.size() - 1)); \n else\n curr.add(nums[i]);\n backtrack(i + 1, curr, nums);\n\t//I would highly suggest debug this code to understand how this "remove" part works \n curr.remove(curr.size() - 1); //important step we removing last element to maintain correct subset on the next iteration\n }\n }\n\n}\n```\n\n## Optimized solution\nOnce we nailed backtracking and how this useless ArrayList works we can come up with better solution (after looking at defferent solution at Discuss section)\nIdea: \n1. We could pass betwise-OR of subset as an argument in backtrack fucntion \n```\npublic class Solution {\n int count=0;\n public int countMaxOrSubsets(int[] nums) {\n int max = 0;\n for(int i:nums)\n max = max | i;\n backtrack(nums,0,max, 0);\n return count;\n }\n\n private void backtrack(int[] nums,int first,int max, int curr){\n if(max == curr)\n count++;\n if(first>=nums.length) return;\n\n for(int i = first;i<nums.length;i++){\n backtrack(nums,i+1,max,curr|nums[i]);\n }\n }\n}\n```\n**Please upvote if you find this solution helpfull.\nThank you !** | 6 | 0 | ['Backtracking', 'Java'] | 1 |
count-number-of-maximum-bitwise-or-subsets | C++ | easy solution with explanation. beats 100% cpp submission | c-easy-solution-with-explanation-beats-1-6799 | The problem is another version of subset sum. Here, we need to calculate OR of every non empty subset instead of sum.\n\nTo generate all possible subset, each s | solaimanhosen | NORMAL | 2021-10-17T04:42:27.496402+00:00 | 2021-10-17T05:00:06.713857+00:00 | 890 | false | The problem is another version of subset sum. Here, we need to calculate OR of every non empty subset instead of sum.\n\n*To generate all possible subset, each step we need to make two decisons. We will take this number to result or leave it. At the end, if at least one number is taken ( no empty subset ), we will check the sum.*\n\n**Time Complexity**: O(2^n) ( **Subset Sum problem using a backtracking approach which will take O(2^n)** ).\n**Space Complexity**: O(1)\n\n\n```\nclass Solution {\n int maxSum;\n int maxSumCount;\n int length;\n \n void find(vector<int>& nums, int sum, int taken, int s) {\n if (s == length) {\n if (taken) {\n if (sum == maxSum) maxSumCount++;\n else if (sum > maxSum) {\n maxSum = sum;\n maxSumCount = 1;\n }\n }\n return;\n }\n find(nums, sum | nums[s], taken + 1, s + 1);\n find(nums, sum, taken, s + 1);\n }\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n length = nums.size();\n maxSum = INT_MIN;\n maxSumCount = 0;\n \n find(nums, 0, 0, 0);\n return maxSumCount;\n }\n};\n``` | 6 | 1 | ['Backtracking', 'C'] | 1 |
count-number-of-maximum-bitwise-or-subsets | [Python3] Dynamic Programming + Bit Manipulation + Greedy - Detailed Solution | python3-dynamic-programming-bit-manipula-xzyv | Intuition\n Describe your first thoughts on how to solve this problem. \n- the more numbers added into current number by or operation, the more chance the curre | dolong2110 | NORMAL | 2024-10-18T19:39:36.861251+00:00 | 2024-10-18T19:39:36.861285+00:00 | 36 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- the more numbers added into current number by `or` operation, the more chance the current number incresase. Thus, the maximum or of `nums` - `max_or` is just the `or` operation in all elements in `nums`\n- After knowing the `max_or` in `nums` we can use backtrack with memoization ~ aka 0-1 Knapsack Dynamic Programming to find the number of subset with all or same as `max_or`\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**1. Calculate `max_or`**\n\n```\nmax_or = 0\nfor num in nums: max_or |= num \n```\n\n- `max_or` is initialized to 0.\n- The code iterates through each number `num` in the input list `nums`.\n- `|=` is the bitwise OR assignment operator. It performs a bitwise OR operation between `max_or` and `num` and assigns the result back to `max_or`.\n- This loop effectively calculates the bitwise OR of all numbers in the list, which will be the maximum possible OR value achievable from any subset.\n\n**2. Define `dp` with Memoization**\n\n```\n@cache\ndef dp(i: int, cur_or: int) -> int:\n if i == len(nums): return cur_or == max_or\n return dp(i + 1, cur_or) + dp(i + 1, cur_or | nums[i])\n```\n\n- `@cache` is a decorator that adds memoization to the `dp` function. This means the results of `dp` for specific input values (`i`, `cur_or`) will be stored. If `dp` is called again with the same inputs, the cached result is returned instead of recalculating it, significantly improving performance.\n- `dp(i: int, cur_or: int) -> int:` This defines a recursive function named `dp` that takes two arguments:\n - `i`: An index representing the current position in the `nums` list.\n - `cur_or`: The current bitwise OR value of the subset being considered.\n- `if i == len(nums): return cur_or == max_or`: This is the base case of the recursion. If `i` reaches the end of the list `len(nums)`, it checks if the `cur_or` is equal to the `max_or` calculated earlier. It returns `1` if they are equal (meaning this subset achieves the maximum OR) and `0` otherwise.\n- `return dp(i + 1, cur_or) + dp(i + 1, cur_or | nums[i])`: This is the recursive step. It explores two possibilities:\n - `dp(i + 1, cur_or)`: Excludes the current number `nums[i]` from the subset and recursively calls `dp` with the next index `i + 1` and the same `cur_or`.\n - `dp(i + 1, cur_or | nums[i])`: Includes the current number `nums[i]` in the subset by performing a bitwise OR between `cur_or` and `nums[i]` and recursively calls `dp` with the next index `i + 1` and the updated `cur_or`.\n - The function returns the sum of the results from these two recursive calls, effectively counting all subsets that achieve the `max_or`.\n\n**3. Call `dp` and Return Result**\n\n```\nreturn dp(0, 0)\n```\n\n- This line initiates the recursive process by calling `dp` with the initial values:\n - `i = 0`: Start from the beginning of the `nums` list.\n - `cur_or = 0`: The initial bitwise OR value is `0`.\n\nThe result of this call (the total count of subsets with maximum OR) is returned as the output of the countMaxOrSubsets function.\nIn essence, the code uses a recursive approach with memoization `@cache` to efficiently explore all possible subsets of the input list and count those whose bitwise OR equals the maximum possible OR value.\n\n\n# Complexity\n- Time complexity: $$O(N * MAX)$$ with `N` is length of `nums` and `MAX` is `max_or` of `nums`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N * MAX)$$ with `N` is length of `nums` and `MAX` \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n max_or = 0\n for num in nums: max_or |= num\n @cache\n def dp(i: int, cur_or: int) -> int:\n if i == len(nums): return cur_or == max_or\n return dp(i + 1, cur_or) + dp(i + 1, cur_or | nums[i])\n return dp(0, 0)\n``` | 5 | 0 | ['Array', 'Dynamic Programming', 'Backtracking', 'Bit Manipulation', 'Python3'] | 0 |
count-number-of-maximum-bitwise-or-subsets | Count Maximum OR Subsets Using Bit Masking | Java | C++ | Video Solution | count-maximum-or-subsets-using-bit-maski-2b8f | Intuition, approach, and complexity dicussed in video solution in detail\nhttps://youtu.be/wO_4VjvrqQQ\n# Code\nJava []\nclass Solution {\n public int countM | Lazy_Potato_ | NORMAL | 2024-10-18T12:42:18.355684+00:00 | 2024-10-18T12:42:18.355709+00:00 | 749 | false | # Intuition, approach, and complexity dicussed in video solution in detail\nhttps://youtu.be/wO_4VjvrqQQ\n# Code\n``` Java []\nclass Solution {\n public int countMaxOrSubsets(int[] nums) {\n int size = nums.length;\n int maxOR = 0, maxORCnt = 0;\n int totalSS = (1 << size) - 1;\n for(int ssMask = 1; ssMask <= totalSS ; ssMask++){\n int currOR = 0;\n for(int indx = 0; indx < size; indx++){\n if(((1 << indx) & ssMask) != 0){\n currOR |= nums[indx];\n }\n }\n if(currOR == maxOR){\n maxORCnt++;\n }else if(currOR > maxOR){\n maxOR = currOR;\n maxORCnt = 1;\n }\n }\n return maxORCnt;\n }\n}\n```\n```cpp []\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int size = nums.size();\n int maxOR = 0, maxORCnt = 0;\n int totalSS = (1 << size) - 1;\n for (int ssMask = 1; ssMask <= totalSS; ssMask++) {\n int currOR = 0;\n for (int indx = 0; indx < size; indx++) {\n if ((1 << indx) & ssMask) {\n currOR |= nums[indx];\n }\n }\n if (currOR == maxOR) {\n maxORCnt++;\n } else if (currOR > maxOR) {\n maxOR = currOR;\n maxORCnt = 1;\n }\n }\n return maxORCnt;\n }\n};\n\n``` | 5 | 0 | ['Array', 'Bit Manipulation', 'Enumeration', 'C++', 'Java'] | 1 |
count-number-of-maximum-bitwise-or-subsets | BackTracking Approach | 99.43% Beats | Beginner friendly | backtracking-approach-9943-beats-beginne-dc2a | Intuition\nThe problem is about finding subsets that produce the maximum possible bitwise OR. First, compute the maximum OR by applying the OR operation across | nagastu02 | NORMAL | 2024-10-18T04:10:35.230435+00:00 | 2024-10-18T04:10:35.230464+00:00 | 902 | false | # Intuition\nThe problem is about finding subsets that produce the maximum possible bitwise OR. First, compute the maximum OR by applying the OR operation across all elements of the array. After that, use a backtracking approach to generate all possible subsets and count how many produce this maximum OR. We can also optimize the subset generation by terminating early if the current subset\'s OR already matches the maximum OR.\n\n# Approach\n1. **Calculate the maximum OR of the entire arra**y.\n - Perform an OR operation on all elements of the array to find the maximum OR.\n2. **Backtrack to generate all subsets**:\n - Use a backtracking function to explore subsets. At each step, decide whether to include or exclude the current element.\n - If at any point the OR of the current subset matches the maximum OR, use the remaining elements directly to speed up the process by counting all remaining subsets.\n3. **Count subsets**:\n - For each subset, if its OR matches the maximum OR, count it.\n# Complexity\n- Time complexity: O(2^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```java []\nclass Solution {\n public int countMaxOrSubsets(int[] nums) {\n int maxOR = 0;\n for (int num : nums) {\n maxOR |= num;\n }\n \n return backtrack(nums, maxOR, 0, 0);\n }\n\n private int backtrack(int[] nums, int maxOR, int index, int currentOR) {\n if (index == nums.length) {\n return currentOR == maxOR ? 1 : 0;\n }\n \n if (currentOR == maxOR) {\n return 1 << (nums.length - index);\n }\n \n return backtrack(nums, maxOR, index + 1, currentOR | nums[index]) +\n backtrack(nums, maxOR, index + 1, currentOR);\n }\n}\n```\n``` c++ []\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int maxOR = 0;\n for (int num : nums) {\n maxOR |= num;\n }\n return backtrack(nums, maxOR, 0, 0);\n }\n\nprivate:\n int backtrack(vector<int>& nums, int maxOR, int index, int currentOR) {\n if (index == nums.size()) {\n return currentOR == maxOR ? 1 : 0;\n }\n if (currentOR == maxOR) {\n return 1 << (nums.size() - index);\n }\n int include = backtrack(nums, maxOR, index + 1, currentOR | nums[index]);\n int exclude = backtrack(nums, maxOR, index + 1, currentOR);\n return include + exclude;\n }\n};\n\n// Example usage\nint main() {\n Solution sol;\n vector<int> nums = {3, 1, 5};\n cout << sol.countMaxOrSubsets(nums) << endl; // Output: 6\n return 0;\n}\n```\n``` python []\nclass Solution:\n def countMaxOrSubsets(self, nums):\n # Step 1: Find the maximum possible OR\n maxOR = 0\n for num in nums:\n maxOR |= num\n \n # Step 2: Backtrack to count subsets that yield the maximum OR\n return self.backtrack(nums, maxOR, 0, 0)\n\n def backtrack(self, nums, maxOR, index, currentOR):\n # Base case: if we reached the end of the array\n if index == len(nums):\n return 1 if currentOR == maxOR else 0\n \n # Optimization: If current OR already matches max OR, count remaining subsets\n if currentOR == maxOR:\n return 1 << (len(nums) - index)\n \n # Explore both including and excluding the current element\n include = self.backtrack(nums, maxOR, index + 1, currentOR | nums[index])\n exclude = self.backtrack(nums, maxOR, index + 1, currentOR)\n \n return include + exclude\n\n# Example usage\nsol = Solution()\nnums = [3, 1, 5]\nprint(sol.countMaxOrSubsets(nums)) # Output: 6\n```\n``` javascript []\nvar countMaxOrSubsets = function(nums) {\n let maxOR = 0;\n for (let num of nums) {\n maxOR |= num;\n }\n return backtrack(nums, maxOR, 0, 0);\n};\n\nfunction backtrack(nums, maxOR, index, currentOR) {\n if (index === nums.length) {\n return currentOR === maxOR ? 1 : 0;\n }\n if (currentOR === maxOR) {\n return 1 << (nums.length - index);\n }\n let include = backtrack(nums, maxOR, index + 1, currentOR | nums[index]);\n let exclude = backtrack(nums, maxOR, index + 1, currentOR);\n return include + exclude;\n}\n\n// Example usage\nconst nums = [3, 1, 5];\nconsole.log(countMaxOrSubsets(nums)); // Output: 6\n```\n | 5 | 0 | ['Array', 'Backtracking', 'Bit Manipulation', 'Enumeration', 'Python', 'C++', 'Java', 'JavaScript'] | 4 |
count-number-of-maximum-bitwise-or-subsets | Straight Forward approach💯🫡 | easy to understand✅✅✅ | C++👑 | straight-forward-approach-easy-to-unders-paxi | \n\n# Code\ncpp []\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int n = nums.size();\n int m = 0, c = 0;\n\n | ritik6g | NORMAL | 2024-10-18T00:22:27.388217+00:00 | 2024-10-18T00:22:27.388242+00:00 | 1,303 | false | \n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int n = nums.size();\n int m = 0, c = 0;\n\n for (int x : nums) {\n m |= x;\n }\n\n int t = 1 << n;\n for (int mask = 1; mask < t; ++mask) {\n int o = 0;\n for (int i = 0; i < n; ++i) {\n if (mask & (1 << i)) {\n o |= nums[i];\n }\n }\n if (o == m) {\n ++c;\n }\n }\n return c;\n }\n};\n\n``` | 5 | 0 | ['C++'] | 2 |
count-number-of-maximum-bitwise-or-subsets | C++ || Recursion | c-recursion-by-aditya_pratap1-8urp | The maximum OR value possible for any subset of an array is the OR of all values in the array!\nAfter calculating the maximum OR possible, we\'ll find OR of all | aditya_pratap1 | NORMAL | 2022-02-24T05:47:39.793826+00:00 | 2022-04-19T11:23:18.588856+00:00 | 587 | false | The **maximum OR value possible for any subset of an array is the OR of all values in the array!**\nAfter calculating the maximum OR possible, we\'ll find OR of all subsets & check if it is equal to maximum OR :\n```\nint recur(vector<int>&nums,int idx,int currOr,int maxOr){\n if(idx < 0){\n return currOr == maxOr;\n }\n return (\n recur(nums,idx-1,currOr,maxOr) // not-including element at \'idx\' in subset\n + recur(nums,idx-1,currOr | nums[idx],maxOr) // including element at \'idx\' in subset\n );\n }\n \n int countMaxOrSubsets(vector<int>& nums) {\n \n int maxOr = 0;\n for(auto num:nums){\n maxOr |= num;\n }\n \n return recur(nums,nums.size()-1,0,maxOr);\n }\n``` | 5 | 0 | ['Recursion', 'C'] | 2 |
count-number-of-maximum-bitwise-or-subsets | Python3 - bitmask | dp | python3-bitmask-dp-by-zhuzhengyuan824-r13l | See more similar bitmask dp type questions here: https://leetcode.com/discuss/general-discussion/1125779/Dynamic-programming-on-subsets-with-examples-explained | zhuzhengyuan824 | NORMAL | 2021-10-17T07:14:49.054509+00:00 | 2021-10-17T07:14:49.054549+00:00 | 386 | false | See more similar `bitmask dp` type questions here: https://leetcode.com/discuss/general-discussion/1125779/Dynamic-programming-on-subsets-with-examples-explained\n\n``` py\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n N = len(nums)\n dp = [-1] * (1<<N)\n dp[0] = 0\n for mask in range(1<<N):\n for j in range(N):\n if mask & (1<<j):\n neib = dp[mask ^ (1<<j)]\n dp[mask] = neib|nums[j]\n return dp.count(max(dp))\n \n``` | 5 | 0 | ['Bitmask', 'Python', 'Python3'] | 1 |
count-number-of-maximum-bitwise-or-subsets | C++ || SIMPLE RECURSION || BEGINNER FRIENDLY | c-simple-recursion-beginner-friendly-by-5ifmy | \nclass Solution {\npublic:\n int count=0;\n int countMaxOrSubsets(vector<int>& nums) {\n long long bitOr=nums[0];\n for(int i=1;i<nums.size | VineetKumar2023 | NORMAL | 2021-10-17T04:18:15.467330+00:00 | 2021-10-17T04:18:15.467367+00:00 | 272 | false | ```\nclass Solution {\npublic:\n int count=0;\n int countMaxOrSubsets(vector<int>& nums) {\n long long bitOr=nums[0];\n for(int i=1;i<nums.size();i++)\n bitOr|=nums[i];\n subsets(nums,0,0,bitOr);\n return count;\n }\n void subsets(vector<int>& nums,int i,int now,int bitOr)\n {\n if(i==nums.size())\n return;\n \n int t=now|nums[i];\n if(t==bitOr)\n count++;\n subsets(nums,i+1,t,bitOr);\n subsets(nums,i+1,now,bitOr);\n }\n};\n``` | 5 | 0 | [] | 1 |
count-number-of-maximum-bitwise-or-subsets | Simple Search | simple-search-by-votrubac-q3vv | We can add memoisation, but it is easy to verify that we do not need it. The runtime is just a few ms already.\n\nC++\ncpp\nint dfs(vector<int>& n, int i, int c | votrubac | NORMAL | 2021-10-17T04:01:40.909348+00:00 | 2021-10-17T05:58:08.791162+00:00 | 227 | false | We can add memoisation, but it is easy to verify that we do not need it. The runtime is just a few ms already.\n\n**C++**\n```cpp\nint dfs(vector<int>& n, int i, int cur_or, int max_or) {\n if (i >= n.size())\n return max_or == cur_or;\n else\n return dfs(n, i + 1, cur_or, max_or) + dfs(n, i + 1, cur_or | n[i], max_or);\n}\nint countMaxOrSubsets(vector<int>& n) {\n return dfs(n, 0, 0, accumulate(begin(n), end(n), 0, bit_or<int>()));\n}\n``` | 5 | 4 | [] | 1 |
count-number-of-maximum-bitwise-or-subsets | Simple py,JAVA code using recursion!! | simple-pyjava-code-using-recursion-by-ar-079a | Similar question\n\n- Try solving this question : 78. Subsets\n- SOLUTION: "Click here for solution"\n\n---\n\n\n# Approach:Recursion\n Describe your approach t | arjunprabhakar1910 | NORMAL | 2024-10-18T19:23:00.267386+00:00 | 2024-10-18T19:28:10.143038+00:00 | 74 | false | # Similar question\n\n- Try solving this question : [78. Subsets](https://leetcode.com/problems/subsets/description/)\n- SOLUTION: ["Click here for solution"](https://leetcode.com/problems/subsets/solutions/5932957/simple-py-java-code-using-recursion)\n\n---\n\n\n# Approach:Recursion\n<!-- Describe your approach to solving the problem. -->\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- My idea is simple,First generate `result` which contains all subset of `nums`.Then find the largest `max_or` value and it length as `count`.Let me tell how I arived there.\n- I found `subset_or` which is the value for each `subset` in `result`.\n- If the `subset_or` value is greater than `max_or` value,the we reintialise `count` to `1`. \n- If they they are same we increase the `count`.\n- By doing this process we arrive at `max_or` value of `nums` with it\'s count the `count`.\n\n\n# Complexity\n- Time complexity:$$O(n.2^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nGenerating all possible susbet takes $$O(2^n)$$\nCalaculating bitwise OR for each susbset $$O(n)$$\n\n# Code\n```Python3 []\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n result=[]\n def helper(subset,nums):\n if not nums:\n result.append(subset)\n return\n helper(subset+[nums[0]],nums[1:])\n helper(subset,nums[1:])\n helper([],nums)\n #print(result)\n max_or_value = 0\n count = 0\n for subset in result:\n subset_or = 0\n for num in subset:\n subset_or |= num\n if subset_or > max_or_value:\n max_or_value = subset_or\n count = 1\n elif subset_or == max_or_value:\n count += 1\n return count\n```\n```java []\nclass Solution {\n public void helper(int[] nums,List<List<Integer>> result,List<Integer> subset,int n){\n if(n==nums.length){\n result.add(new ArrayList<>(subset));\n return;\n }\n subset.add(nums[n]);\n helper(nums,result,subset,n+1);\n subset.remove(subset.size()-1);\n helper(nums,result,subset,n+1);\n }\n public int calculateMaxOrSubset(List<List<Integer>> result){\n int max_or_value=0,count=0;\n for(List<Integer> counter:result){\n int subset_or=0;\n for(int num:counter){\n subset_or |=num;\n }\n if(subset_or>max_or_value){\n count=1;\n max_or_value=subset_or;\n }\n else if(max_or_value==subset_or){\n count++;\n }\n }\n return count;\n }\n public int countMaxOrSubsets(int[] nums) {\n List<List<Integer>> result=new ArrayList<>();\n helper(nums,result,new ArrayList<>(),0);\n return calculateMaxOrSubset(result);\n }\n}\n``` | 4 | 0 | ['Array', 'Recursion', 'Java', 'Python3'] | 0 |
count-number-of-maximum-bitwise-or-subsets | Easy Solve.........🔥🔥🔥🔥🔥 | easy-solve-by-pritambanik-skr6 | 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 | PritamBanik | NORMAL | 2024-10-18T18:25:02.311006+00:00 | 2024-10-18T18:25:02.311038+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: 100%\u2705\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```c []\nint countMaxOrSubsets(int* a, int n) {\n int or = a[0], cnt = 0;\n for (int i=1;i<n;i++) or |= a[i];\n void subsets(int i, int candidate) {\n if (candidate == or) {\n cnt += (1 << (n - i)); \n return;\n }\n while (i<n) {\n subsets(i + 1, candidate | a[i]);\n i++;\n } \n }\n subsets(0, 0);\n return cnt;\n}\n``` | 4 | 0 | ['Array', 'Backtracking', 'Bit Manipulation', 'C', 'Enumeration'] | 0 |
count-number-of-maximum-bitwise-or-subsets | C++ Solution || Simple Recursion || Detailed Explanation | c-solution-simple-recursion-detailed-exp-mjvj | Intuition\nThe problem requires us to count how many subsets of the given array have the maximum possible bitwise OR value. The idea is to:\n1. Calculate the ma | Rohit_Raj01 | NORMAL | 2024-10-18T06:22:08.848491+00:00 | 2024-10-18T06:22:08.848522+00:00 | 368 | false | # Intuition\nThe problem requires us to count how many subsets of the given array have the maximum possible bitwise OR value. The idea is to:\n1. **Calculate the maximum possible OR** value by OR-ing all elements of the array.\n2. **Recursively explore all subsets**, keeping track of the OR value of the current subset.\n3. **For each subset**, check if its OR value equals the maximum OR value. If it does, increment the count.\n\n# Approach\n1. **Calculate the maximum OR value**:\n - First, find the maximum possible OR value by applying the OR operation across all elements in the array. This will be the value that we want our subsets to achieve.\n2. **Recursive backtracking**:\n - Use a recursive function `solve` to explore all possible subsets. For each element, you have two choices: either include the current element in the subset or skip it.\n - Keep track of the current OR value (`tempOr`) as you build subsets. \n - When you reach the end of the array (base case), compare the OR value of the subset (`tempOr`) with the maximum OR value (`maxOr`). \n - If they are equal, increment the counter `cnt`.\n3. **Return the count**:\n - The result is the count of all subsets whose OR value matches the maximum OR value.\n\n# Complexity\n- Time complexity: $$O(2^N)$$ \n\n- Space complexity: $$O(N)$$ \n\n# Code\n```cpp []\nclass Solution {\npublic:\n void solve(int ind, int tempOr, vector<int>& nums, int& maxOr, int& cnt) {\n int n = nums.size();\n if (ind == n) {\n if (tempOr == maxOr) {\n cnt++;\n }\n return;\n }\n solve(ind + 1, tempOr | nums[ind], nums, maxOr, cnt);\n solve(ind + 1, tempOr, nums, maxOr, cnt);\n }\n int countMaxOrSubsets(vector<int>& nums) {\n int n = nums.size();\n int maxOr = 0;\n for (int i = 0; i < n; i++) {\n maxOr = maxOr | nums[i];\n }\n int tempOr = 0;\n int ans = 0;\n solve(0, tempOr, nums, maxOr, ans);\n return ans;\n }\n};\n```\n\n# *Quote of the Day*\n> ***A recursive function calls itself; a good programmer calls their recursive function well.***\n\n\n\n\n\n | 4 | 0 | ['Array', 'Backtracking', 'Bit Manipulation', 'C++'] | 1 |
count-number-of-maximum-bitwise-or-subsets | Simple Approach | 🌟 Beats 100.00% 🚀 || Step-by-Step Breakdown 💯🔥 | simple-approach-beats-10000-step-by-step-lyuh | \n\n# Intuition\nThe goal of the code is to compute how many subsets of the list nums can produce the maximum possible bitwise OR.\n# Approach\n\n1. Initialize: | hemanta8338 | NORMAL | 2024-10-18T05:52:38.962646+00:00 | 2024-10-18T05:52:38.962686+00:00 | 311 | false | \n\n# Intuition\nThe goal of the code is to compute how many subsets of the list nums can produce the maximum possible bitwise OR.\n# Approach\n\n1. **Initialize**:\n - Initialize `dp` as a hash map, starting with `{0: 1}` to keep track of the count of ways to achieve different bitwise OR values.\n - `max_or` keeps track of the cumulative maximum OR of all elements.\n\n2. **Iterate over `nums`**:\n - For each `num` in `nums`, iterate over the current OR values stored in `dp` (using `list(dp.items())` to avoid modifying it during iteration).\n - For each `(v, c)` pair in `dp`, update `dp` by increasing the count of the new OR value `v | num`.\n\n3. **Update `max_or`**:\n - After processing each `num`, update `max_or` to include it (`max_or |= num`).\n\n4. **Final Output**:\n - Return `dp[max_or]`.\n\n# Complexity\n- Time complexity:$$O(n * m)$$\n\n- Space complexity:$$O(n * m)$$\n\n# Code\n```python3 []\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n dp = Counter([0])\n max_or = 0\n for num in nums:\n for val, count in list(dp.items()):\n dp[val | num] += count\n max_or |= num\n\n return dp[max_or]\n``` | 4 | 0 | ['Array', 'Dynamic Programming', 'Bit Manipulation', 'Bitmask', 'Python', 'Python3'] | 0 |
count-number-of-maximum-bitwise-or-subsets | [Golang] Backtracking | Simple Solution | golang-backtracking-simple-solution-by-s-i2en | Approach\n- The maximum OR is the OR of the array. We can find it by traversing the array and performing OR operation for every number in it. That value will be | suoncha | NORMAL | 2024-10-18T03:58:11.411120+00:00 | 2024-10-18T03:58:11.411158+00:00 | 51 | false | # Approach\n- The maximum OR is the OR of the array. We can find it by traversing the array and performing OR operation for every number in it. That value will be saved to `target`\n- Once we found it, perform backtrack starting from the first index to generate all possible subsets. Instead of tracking the entire subset, we just need to track the OR of each subset with `cur`\n- If OR of the current subset equals to `target`, add 1 to `ans`\n- Return `ans` once we have visited all possible subsets\n\n# Complexity\n- Time complexity:\nO(2^n)\n\n- Space complexity:\nO(n)\n\n# Code\n```golang []\nfunc countMaxOrSubsets(nums []int) int {\n target, ans := 0, 0\n for _, num := range nums {\n target |= num\n }\n\n var backtrack func(int, int)\n backtrack = func(start, cur int) {\n if cur == target {\n ans++\n }\n for i := start; i < len(nums); i++ {\n backtrack(i + 1, cur | nums[i])\n }\n }\n backtrack(0, 0)\n return ans\n}\n``` | 4 | 0 | ['Go'] | 0 |
count-number-of-maximum-bitwise-or-subsets | C++ ✅ | Bitmasking 🚀 | c-bitmasking-by-jatin1510-ylr9 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe key idea here is to recognize that the bitwise OR operation tends to grow the more | jatin1510 | NORMAL | 2024-10-18T03:30:10.365339+00:00 | 2024-10-18T03:30:10.365374+00:00 | 757 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe key idea here is to recognize that the bitwise OR operation tends to grow the more elements you include in the subset, since the OR operation accumulates set bits from all the elements. Our goal is to find the maximum bitwise OR we can achieve with any subset and then count how many subsets yield that maximum result.\n\nOne intuitive way to solve this is to consider that for any subset, the more distinct set bits (1s) we have in binary representation, the closer we get to the maximum possible OR. Thus, once we calculate the maximum OR for the entire set, our task reduces to counting how many subsets achieve this value.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Compute the maximum possible bitwise OR by performing the OR operation across all elements in the array.\n2. Generate all possible subsets using bit manipulation. For each subset, calculate its bitwise OR.\n3. Compare the OR of each subset to the maximum OR calculated in step 1. If they match, increase the count.\n4. Return the total count of such subsets.\n\n# Complexity\n- Time complexity: $$O(n * 2^n)$$\nCalculating the maximum bitwise OR takes $$O(n)$$, where n is the number of elements in the array. \nIterating through all $$2^n$$ subsets and computing their OR takes $$O(n * 2^n)$$, as each subset takes $$O(n)$$ operations.\n\n- Space complexity: $$O(1)$$\nThe space complexity is $$O(1)$$ apart from the input size, as we use only a few additional variables.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int orr = accumulate(begin(nums), end(nums), 0, [&](int a, int b) {\n return a | b;\n });\n\n int n = nums.size(), ans = 0;\n for (int i = 0; i < (1 << n); i++) {\n int cur = 0;\n for (int index = 0; index < n; index++) {\n if ((i >> index) & 1) {\n cur |= nums[index];\n }\n }\n ans += (cur == orr);\n }\n\n return ans;\n }\n};\n\n``` | 4 | 0 | ['Bit Manipulation', 'Enumeration', 'C++'] | 0 |
count-number-of-maximum-bitwise-or-subsets | 💥💥Easy 3 line solution Beats 80%✅✅O(2^n) | easy-3-line-solution-beats-80o2n-by-shad-hnjq | Intuition\nTrying all Combinations (same as combination sum question)\n# Approach\nTrying all Combinations\n\n\u26A1To get all the possible combinations\uD83D\u | shady__ | NORMAL | 2024-10-18T00:43:12.960473+00:00 | 2024-10-18T00:43:12.960505+00:00 | 405 | false | # Intuition\nTrying all Combinations (same as combination sum question)\n# Approach\nTrying all Combinations\n\n\u26A1To get all the possible combinations\uD83D\uDFE2\n\u26A1At each element we got two choises take that element or leave it\n\u26A1The base Case is reaching the end of the array\n\n\n# Complexity\n- Time complexity:\nO(2^n)\n\n- Space complexity:\n- O(1)\n\n# Code\n```cpp []\nclass Solution {\n int rec(vector<int>& nums,int&OR,int o=0,int i=0){\n if(nums.size()==i){if(o==OR)return 1;\n return 0;}\n return rec(nums,OR,o,i+1)+rec(nums,OR,o|nums[i],i+1);\n }\npublic: \n int countMaxOrSubsets(vector<int>& nums) {\n int OR=0;\n for(int&a:nums) OR=OR|a;\n return rec(nums,OR);\n }\n};\n``` | 4 | 0 | ['Backtracking', 'C++'] | 3 |
count-number-of-maximum-bitwise-or-subsets | BRUTE FORCE 2^n || C++ | brute-force-2n-c-by-ganeshkumawat8740-6z99 | Code\n\nclass Solution {\npublic:\n void solve(int i,int x,int k,vector<int> &v,int &ans){\n // if(x==k)ans++;\n if(i>=v.size()){ans += (x==k); | ganeshkumawat8740 | NORMAL | 2023-06-13T03:13:13.654943+00:00 | 2023-06-13T03:13:13.654963+00:00 | 486 | false | # Code\n```\nclass Solution {\npublic:\n void solve(int i,int x,int k,vector<int> &v,int &ans){\n // if(x==k)ans++;\n if(i>=v.size()){ans += (x==k);return;}\n solve(i+1,x,k|v[i],v,ans);\n solve(i+1,x,k,v,ans);\n }\n int countMaxOrSubsets(vector<int>& nums) {\n int x = 0;\n for(auto &i: nums){\n x |= i;\n }\n int ans = 0;\n solve(0,x,0,nums,ans);\n return ans;\n }\n};\n``` | 4 | 0 | ['Array', 'Backtracking', 'Bit Manipulation', 'C++'] | 0 |
count-number-of-maximum-bitwise-or-subsets | Simple Solution in Java | simple-solution-in-java-by-s34-5h15 | Hints\n- The maximum bitwise-OR is the bitwise-OR of the whole array (max)\n- Use bitwise operation to find all the possible subset of given array\n- If max==th | s34 | NORMAL | 2022-02-13T12:29:49.396565+00:00 | 2022-02-13T12:29:49.396596+00:00 | 162 | false | **Hints**\n- The maximum bitwise-OR is the bitwise-OR of the whole array (max)\n- Use bitwise operation to find all the possible subset of given array\n- If max==the OR of subset, count++\n```\nclass Solution {\n public int countMaxOrSubsets(int[] nums) {\n int max=0,tmp=0,count=0;\n //The maximum bitwise-OR is the bitwise-OR of the whole array\n for(int i=0;i<nums.length;i++){\n max=max|nums[i];\n }\n \n for(int i=0;i<(1<<nums.length);i++){\n tmp=0;\n for(int j=0;j<nums.length;j++){\n if((i&(1<<j))>0){\n tmp=tmp|nums[j];\n }\n }\n if(tmp==max){\n count++;\n }\n }\n \n return count;\n }\n}\n```\nPlease **upvote**, if you like the solution:) | 4 | 0 | [] | 0 |
count-number-of-maximum-bitwise-or-subsets | [C++] Recursive DP solution | c-recursive-dp-solution-by-marcos_999-jq4a | This Problem is similar to number of subset with given sum.\nSo the basic approch is that pick one by one element and calculate the OR and check if it equal to | marcos_999 | NORMAL | 2021-10-21T05:54:47.768322+00:00 | 2021-10-21T05:54:47.768368+00:00 | 407 | false | This Problem is similar to number of subset with given sum.\nSo the basic approch is that pick one by one element and calculate the OR and check if it equal to resultant OR.\nFirst try to write recursive code and then do the memorization to reduce the time complexity.\n\n``` \nclass Solution {\npublic:\n vector<vector<int>> dp;\n int solve(int i, vector<int> a, int oor, int xoor) {\n if(i == a.size()) {\n if(oor == xoor) return 1;\n return 0;\n }\n if(dp[i][oor] != -1) return dp[i][oor];\n dp[i][oor] = solve(i + 1, a, oor | a[i], xoor) + solve(i + 1, a, oor, xoor);\n return dp[i][oor];\n }\n int countMaxOrSubsets(vector<int>& a) {\n int all_or = 0;\n for(auto i : a) all_or |= i;\n dp = vector<vector<int>> (a.size() + 1, vector<int>(all_or + 1, -1));\n return solve(0, a, 0, all_or);\n }\n};\n``` | 4 | 0 | ['Dynamic Programming'] | 1 |
count-number-of-maximum-bitwise-or-subsets | Java DFS with pruning beats 100% | java-dfs-with-pruning-beats-100-by-jianw-lsy0 | A simple DFS solution with prunig. Whenever preSum equals sum, there\'s no need to do further recursion calls as all remaining combinations will satisfy the con | jianwu | NORMAL | 2021-10-20T07:15:51.551214+00:00 | 2021-10-20T07:15:51.551258+00:00 | 303 | false | A simple DFS solution with prunig. Whenever `preSum` equals `sum`, there\'s no need to do further recursion calls as all remaining combinations will satisfy the condition. So we can simply add `2^remainCount` will do.\n\n```java\nclass Solution {\n int result;\n int sum;\n public int countMaxOrSubsets(int[] nums) {\n result = 0;\n sum = 0;\n for (int i : nums)\n sum |= i;\n dfs(0, nums, 0);\n return result;\n }\n\n private void dfs(int presum, int[] nums, int idx) {\n if (presum == sum) {\n result += 1 << (nums.length - idx);\n return;\n }\n if (idx == nums.length)\n return;\n dfs(presum | nums[idx], nums, idx+1);\n dfs(presum, nums, idx+1);\n }\n}\n``` | 4 | 0 | [] | 0 |
count-number-of-maximum-bitwise-or-subsets | C++ | Bitmasking | c-bitmasking-by-mohit_ahirwar-hyqn | \nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int n = nums.size(),ans=0,m = nums[0];\n for(int i=1;i<n;i++) m |= n | Mohit_Ahirwar | NORMAL | 2021-10-17T04:51:04.116001+00:00 | 2021-10-17T04:51:04.116037+00:00 | 521 | false | ```\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int n = nums.size(),ans=0,m = nums[0];\n for(int i=1;i<n;i++) m |= nums[i]; // Max-OR : OR of all elements\n int k = 1 << n;\n for(int i=0;i<k;i++){\n int j = i,c=0,l=0;\n while(j > 0){\n if(j&1){\n c |= nums[l];\n }\n l++;\n j = j>>1;\n }\n if(c==m) ans++;\n }\n return ans;\n }\n};\n``` | 4 | 0 | [] | 1 |
count-number-of-maximum-bitwise-or-subsets | [Java] Math + Modified Backtracking 3ms beat 100% after sort Array (with detailed explanation) | java-math-modified-backtracking-3ms-beat-7wfi | Find the maxOR num \n2. Sort array for more efficient backtracking latter\n3. Backtrack the array from the biggest number to smallest one(because the maxOR must | keyi | NORMAL | 2021-10-17T04:43:34.874804+00:00 | 2021-10-17T07:46:28.793162+00:00 | 620 | false | 1. Find the maxOR num \n2. Sort array for more efficient backtracking latter\n3. Backtrack the array from the biggest number to smallest one(because the maxOR must be from the biggest one)\n4. Say the sorted array is `[1,2,3,5]` and we start from the last element 5. when it goes to 2, the `existingOR` is already the maxOR (7 = 5 | 3). So the `remainingElementsNum` is 2([1,2]). Combination is C2-0(choose nothing from 2 elements) + C2-1 (choose 1 element from 2 elements) + C2-2(choose 2 from 2 elements) = `Math.pow(2, remainingElementsNum)` The result is `[5,3], [5,3,1], [5,3,2], [5,3,1,2]` . Backtracking(starts with 5) ends. Next round (starts with 3) starts..\n\nNotes (Math): Cn0 + Cn1 + Cn2 + ... CnN = 2^n, for n >= 1;\n\n\n```\n\nclass Solution {\n private int result = 0;\n private int maxOR;\n private int[] nums;\n \n public int countMaxOrSubsets(int[] nums) {\n if(nums.length == 1){\n return 1;\n }\n \n this.nums = nums;\n\n\t\t// get maxOR \n maxOR = nums[0];\n for(int i = 1; i < nums.length; i++){\n maxOR = maxOR | nums[i];\n }\n \n Arrays.sort(nums);\n\t\t// Start from the biggest number\n for(int i = nums.length - 1; i >= 0; i--){\n backtracking(nums[i], i - 1);\n }\n\t\t\n return result;\n }\n \n private void backtracking(int existingOR, int index){\n\n\t\t// it means we can choose (0, 1, ... index + 1) number from the first (index + 1) elements\n if(existingOR == maxOR){\n int remainingElementsNum = index + 1;\n result += Math.pow(2, remainingElementsNum);\n\t\t\t// Backtracking ends here as we only need to know the combination size instead of the actual combination array\n return;\n }\n\t\t\n for(int i = index; i >= 0; i--){\n backtracking(existingOR | nums[i], i - 1);\n }\n }\n}\n``` | 4 | 0 | ['Math', 'Backtracking', 'Java'] | 1 |
count-number-of-maximum-bitwise-or-subsets | Java || Simple || Easy to Understand | java-simple-easy-to-understand-by-kdhaka-eylo | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | kdhakal | NORMAL | 2025-02-27T16:17:14.237323+00:00 | 2025-02-27T16:17:14.237323+00:00 | 28 | 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 {
int count = 0;
public int countMaxOrSubsets(int[] nums) {
int maxOr = 0;
for(int num : nums) maxOr |= num;
helper(nums, 0, 0, maxOr);
return count;
}
public void helper(int[] nums, int index, int currentOr, int maxOr) {
if(currentOr == maxOr) count++;
for(int i = index; i < nums.length; i++) {
helper(nums, i + 1, currentOr | nums[i], maxOr);
}
}
}
``` | 3 | 0 | ['Java'] | 0 |
count-number-of-maximum-bitwise-or-subsets | Simple C++ solution | Backtracking | simple-c-solution-backtracking-by-saurab-nwza | Intuition\nWe will generate all te subsets using backtracking and check if their bitwise or is the maximum and return the count.\n\n# Approach\n1. Compute the m | saurabhdamle11 | NORMAL | 2024-10-18T14:17:02.817384+00:00 | 2024-10-18T14:17:02.817416+00:00 | 198 | false | # Intuition\nWe will generate all te subsets using backtracking and check if their bitwise or is the maximum and return the count.\n\n# Approach\n1. Compute the maximum bitwise or of all the elements possible.\n2. Generate all possible subsets using recursion and for every subset, check if the xor is equal to maximum possible xor.\n3. If it is, increment the answer.\n\n# Complexity\n- Time complexity:\nO(2^n)\n- Space complexity:\nO(n)\n\n# Code\n```cpp []\nclass Solution {\n\nprivate:\n\n void solve(int ind,vector<int>&nums,int &ans,int m, int &maxor, int ds){\n if(ind==m){\n if(ds==maxor){\n ans++;\n }\n return;\n } \n solve(ind+1,nums,ans,m,maxor,ds|nums[ind]); \n solve(ind+1,nums,ans,m,maxor,ds);\n }\n\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n const int m = nums.size();\n int maxor = 0;\n for(int i:nums){\n maxor|=i;\n }\n int ds=0;int ans=0;\n solve(0,nums,ans,m,maxor,ds);\n return ans;\n }\n};\n\n\n```\n\n``` java []\nclass Solution {\n \n private void solve(int ind, int[] nums, int[] ans, int m, int maxor, int ds) {\n if (ind == m) {\n if (ds == maxor) {\n ans[0]++;\n }\n return;\n } \n solve(ind + 1, nums, ans, m, maxor, ds | nums[ind]); \n solve(ind + 1, nums, ans, m, maxor, ds);\n }\n\n public int countMaxOrSubsets(int[] nums) {\n int m = nums.length;\n int maxor = 0;\n for (int num : nums) {\n maxor |= num;\n }\n int ds = 0;\n int[] ans = {0}; \n solve(0, nums, ans, m, maxor, ds);\n return ans[0];\n }\n}\n\n``` | 3 | 0 | ['Array', 'Backtracking', 'Bit Manipulation', 'Enumeration', 'C++', 'Java'] | 2 |
count-number-of-maximum-bitwise-or-subsets | Beats 100% || Java, Python, C++ detailed solution | beats-100-java-python-c-detailed-solutio-anz0 | Intuition\nThe goal of this problem is to find the number of subsets whose bitwise OR equals the maximum possible bitwise OR of all elements in the array. The b | yashringe | NORMAL | 2024-10-18T10:26:04.099026+00:00 | 2024-10-18T10:26:04.099055+00:00 | 78 | false | # Intuition\nThe goal of this problem is to find the number of subsets whose bitwise OR equals the maximum possible bitwise OR of all elements in the array. The brute-force way to solve this problem would be to generate all possible subsets and compute their OR values. However, this can be optimized by using recursion with pruning to avoid unnecessary computations. The tail array helps us prune branches of the recursion where it is impossible to achieve the maximum OR value by looking ahead.\n# Approach\n1. Calculate Maximum OR:\n\n - Start by calculating the maximum OR that can be achieved by OR\'ing all the elements in the array.\n\n2. Tail Array (Optimization):\n\n - Precompute a tail array where tail[i] represents the OR of all elements from index i to the end of the array. This helps us to prune unnecessary recursive calls by quickly checking if it\'s possible to achieve the maximum OR from the remaining elements.\n\n3. Recursive Function:\n\n - Use a depth-first search (DFS) approach to explore all subsets. For each element, you have two choices: include it in the subset or exclude it.\n- Prune the recursion if the current partial OR combined with the remaining elements cannot achieve the maximum OR.\n- If the current OR matches the maximum OR, return the number of remaining subsets that can be formed (since all of them will have the same OR value).\n\n# Complexity\n- Time complexity:\nThe time complexity is O(2n ) where n is the length of the input array, as we are exploring all possible subsets (which is 2n ).\n\n- Space complexity:\nThe space complexity is O(n) due to the recursion stack and the tail array.\n\n# Code\n```java []\nclass Solution {\n static int[] tail = new int[16]; // Array to store the bitwise OR of tail elements\n int[] nums; // Reference to the input array\n int max; // Variable to store the maximum OR value\n\n public int countMaxOrSubsets(int[] nums) {\n this.nums = nums;\n max = nums[0];\n\n // Calculate the maximum possible OR of all elements in the array\n for (int i = 1; i < nums.length; i++) {\n max |= nums[i];\n }\n\n // Populate the tail array\n int v = 0;\n for (int i = nums.length - 1; i >= 0; i--) {\n v |= nums[i];\n tail[i] = v;\n }\n\n // Start the recursion\n return recurse(0, 0);\n }\n\n int recurse(int i, int partial) {\n // If the current partial OR equals the max, return the count of remaining subsets\n if (partial == max) {\n return 1 << (nums.length - i);\n }\n\n // If we\'ve reached the end of the array or it\'s impossible to achieve the max, return 0\n if (i == nums.length || ((partial | tail[i]) != max)) {\n return 0;\n }//ringewashere\n\n // Recursive step: include or exclude the current element\n return recurse(i+1, partial | nums[i]) // Include the current element\n + recurse(i+1, partial); // Exclude the current element\n }\n}\n\n```\n```Python []\n\nclass Solution:\n def countMaxOrSubsets(self, nums):\n self.nums = nums\n self.max_or = 0\n\n # Calculate the maximum OR value\n for num in nums:\n self.max_or |= num\n \n # Create the tail array\n self.tail = [0] * len(nums)\n v = 0\n for i in range(len(nums) - 1, -1, -1):\n v |= nums[i]\n self.tail[i] = v\n \n # Start the recursion\n return self.recurse(0, 0)\n\n def recurse(self, i, partial):\n # If the current partial OR equals the max, return the count of remaining subsets\n if partial == self.max_or:\n return 1 << (len(self.nums) - i)\n\n # If we\'ve reached the end of the array or it\'s impossible to achieve the max\n if i == len(self.nums) or (partial | self.tail[i]) != self.max_or:\n return 0\n\n # Recursive step: include or exclude the current element\n return self.recurse(i + 1, partial | self.nums[i]) + self.recurse(i + 1, partial)\n\n```\n```Cpp []\nclass Solution {\npublic:\n vector<int> tail; // Tail array to store OR of elements from index i to end\n int max_or; // Maximum OR value\n vector<int> nums; // Reference to the input array\n\n int countMaxOrSubsets(vector<int>& nums) {\n this->nums = nums;\n max_or = nums[0];\n\n // Calculate maximum OR of all elements\n for (int i = 1; i < nums.size(); i++) {\n max_or |= nums[i];\n }\n\n // Populate the tail array\n tail.resize(nums.size());\n int v = 0;\n for (int i = nums.size() - 1; i >= 0; i--) {\n v |= nums[i];\n tail[i] = v;\n }\n\n // Start the recursion\n return recurse(0, 0);\n }\n\n int recurse(int i, int partial) {\n // If partial OR equals max OR, return the number of remaining subsets\n if (partial == max_or) {\n return 1 << (nums.size() - i);\n }\n\n // If end of array is reached or can\'t achieve max OR, return 0\n if (i == nums.size() || ((partial | tail[i]) != max_or)) {\n return 0;\n }\n\n // Recursive step: include or exclude current element\n return recurse(i + 1, partial | nums[i]) + recurse(i + 1, partial);\n }\n};\n\n```\n\n\n\n | 3 | 0 | ['C++', 'Java', 'Python3'] | 0 |
count-number-of-maximum-bitwise-or-subsets | Easy Solution | JavaScript | C++ | Python | easy-solution-javascript-c-python-by-nur-a8b8 | Intuition\n- We enumerate all possible subsets\n- The maximum bitwise-OR is the bitwise-OR of the whole array.\n# Approach\n\n\n### 1. Calculate Maximum OR (max | Nurliaidin | NORMAL | 2024-10-18T08:45:27.219623+00:00 | 2024-10-18T08:45:27.219657+00:00 | 316 | false | # Intuition\n- We enumerate all possible subsets\n- The maximum bitwise-OR is the bitwise-OR of the whole array.\n# Approach\n\n\n### 1. **Calculate Maximum OR (`maxBit`):**\n - First, calculate the maximum possible OR value (`maxBit`) by taking the bitwise OR of all the elements in the array. This value will be the target OR value we are looking for in subsets.\n \n **Example:**\n - If `nums = [3, 1, 5]`, the maximum OR value would be `3 | 1 | 5 = 7`.\n\n### 2. **Generate All Subsets:**\n - To find all subsets, you need to consider every combination of the elements. You can do this recursively or by using bit manipulation.\n \n - **Recursive Approach**: For each element in the array, you have two choices: either include it in the current subset or skip it. Recursively explore both possibilities.\n \n - **Bit Manipulation Approach**: You can represent each subset as a binary number where each bit represents whether a corresponding element from the array is included in the subset.\n\n### 3. **Check OR of Each Subset:**\n - For each subset generated, calculate its OR value and check if it matches `maxBit`. If it does, increment the count.\n\n### 4. **Return the Count of Valid Subsets:**\n - Keep track of how many subsets have their OR value equal to `maxBit`.\n\n### Recursive Approach (Steps):\n- Recursively build subsets by either including or excluding each element.\n- Track the running OR of the current subset.\n- When you reach the end of the array (a complete subset), check if the current subset\'s OR is equal to `maxBit`. If so, increment the result.\n\n# Complexity\n- Time complexity:\n\n$$O(2^n)$$\n- Space complexity:\n\n$$O(1)$$\n# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar countMaxOrSubsets = function(nums) {\n\n let maxBit = 0;\n for (let num of nums) {\n maxBit |= num;\n\n }\n\n let res = 0;\n\n let iteration = ( i, bit_or) => {\n\n if (i >= nums.length) {\n if (bit_or == maxBit) {\n res++;\n }\n return;\n }\n iteration(i+1, bit_or);\n iteration(i+1, bit_or | nums[i]);\n };\n\n iteration(0, 0);\n return res;\n};\n```\n``` cpp []\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int maxBit = 0;\n for (int num: nums) {\n maxBit |= num;\n\n }\n\n int res = 0;\n iteration(res, nums, maxBit, 0, 0);\n return res;\n }\n void iteration (int& res, vector<int>& nums, int& maxBit, int i, int bit_or) {\n\n if (i >= nums.size()) {\n if (bit_or == maxBit) {\n res++;\n }\n return;\n }\n iteration(res, nums, maxBit, i+1, bit_or);\n iteration(res, nums, maxBit, i+1, bit_or | nums[i]);\n };\n};\n```\n``` python []\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n maxBit = 0\n for num in nums:\n maxBit |= num\n\n\n res = [0]\n self.iteration(res, nums, 0, 0, maxBit)\n return res[0]\n \n def iteration(self, res, nums, i, bit_or, maxBit):\n if i >= len(nums):\n if bit_or == maxBit:\n res[0] += 1\n return\n\n\n self.iteration(res, nums, i+1, bit_or, maxBit)\n\n self.iteration(res, nums, i+1, bit_or | nums[i], maxBit)\n``` | 3 | 0 | ['Array', 'Backtracking', 'Bit Manipulation', 'Enumeration', 'C++', 'Python3', 'JavaScript'] | 1 |
count-number-of-maximum-bitwise-or-subsets | Java Clean Solution | java-clean-solution-by-shree_govind_jee-nofi | 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-10-18T04:56:48.668370+00:00 | 2024-10-18T04:56:48.668403+00:00 | 508 | 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```java []\nclass Solution {\n List<Integer> or_list = new ArrayList<>();\n\n private void helper(int[] nums, int sum, int idx) {\n if (idx == nums.length) {\n or_list.add(sum);\n return;\n }\n\n int val = sum | nums[idx];\n helper(nums, val, idx + 1);\n helper(nums, sum, idx + 1);\n }\n\n public int countMaxOrSubsets(int[] nums) {\n helper(nums, 0, 0);\n\n Collections.sort(or_list, Collections.reverseOrder());\n int max = or_list.get(0);\n int res = 0;\n for (var l : or_list) {\n if (max == l)\n res++;\n else\n break;\n }\n return res;\n }\n}\n``` | 3 | 0 | ['Array', 'Backtracking', 'Bit Manipulation', 'Enumeration', 'Java'] | 0 |
count-number-of-maximum-bitwise-or-subsets | C# Solution for Count Number of Maximum Bitwise - OR Subsets Problem | c-solution-for-count-number-of-maximum-b-at79 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is about finding subsets whose bitwise OR equals the maximum possible OR th | Aman_Raj_Sinha | NORMAL | 2024-10-18T03:14:15.868306+00:00 | 2024-10-18T03:14:15.868347+00:00 | 197 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is about finding subsets whose bitwise OR equals the maximum possible OR that can be achieved from the array. Since there are 2^n subsets for an array of length n, and the OR operation accumulates values as elements are added to a subset, we can generate all possible subsets and track the OR for each one. Using bit manipulation (bitmasking) allows us to efficiently iterate through all possible subsets.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tBitwise OR Calculation:\n\t\u2022\tFirst, compute the maximum OR by iterating through all elements of the array and performing the bitwise OR across the entire array. This tells us the value we want to match for the subsets.\n2.\tSubset Generation Using Bitmasking:\n\t\u2022\tEach subset of the array can be represented by a bitmask. A bitmask is an integer where each bit indicates whether a corresponding element is included in the subset.\n\t\u2022\tFor an array of length n, there are 2^n possible subsets, which can be represented by integers from 1 to 2^n - 1. The bit representation of these integers tells us which elements are included in the subset.\n\t\u2022\tFor each bitmask, we calculate the OR of the elements in the subset that correspond to the set bits.\n3.\tCounting Valid Subsets:\n\t\u2022\tFor each subset (bitmask), we compute the bitwise OR of the subset. If the result matches the maximum OR computed earlier, we increment our count of valid subsets.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSubset Generation: For an array of size n, there are 2^n subsets. Each subset is represented by a bitmask, and for each bitmask, we potentially check all n elements to compute the OR.\n\u2022\tIterating over all 2^n subsets: O(2^n)\n\u2022\tFor each subset, checking which elements to include based on the bitmask takes O(n) time in the worst case.\n\u2022\tTherefore, the total time complexity is O(n * 2^n).\nGiven that n <= 16 (as per the problem constraints), this is feasible. The maximum number of subsets is 2^{16} = 65536, which makes this approach efficient enough for the problem.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nBitmasking: The space required to store intermediate results (the OR of the subset and the current bitmask) is minimal. The only significant memory usage comes from the recursion depth or loop iterations, which is proportional to n (the number of elements in the array).\n\u2022\tO(n) space is required to store the subset ORs during computation.\n\u2022\tHence, the total space complexity is O(n).\n\n# Code\n```csharp []\npublic class Solution {\n public int CountMaxOrSubsets(int[] nums) {\n int maxOr = 0;\n int n = nums.Length;\n foreach (int num in nums) {\n maxOr |= num;\n }\n\n int count = 0;\n int totalSubsets = 1 << n; \n \n for (int mask = 1; mask < totalSubsets; mask++) {\n int currentOr = 0;\n for (int i = 0; i < n; i++) {\n if ((mask & (1 << i)) != 0) {\n currentOr |= nums[i];\n }\n }\n if (currentOr == maxOr) {\n count++;\n }\n }\n\n return count;\n }\n}\n``` | 3 | 0 | ['C#'] | 0 |
count-number-of-maximum-bitwise-or-subsets | Easy solution, using backtracking. Daily Question 18/10/24 | easy-solution-using-backtracking-daily-q-7rw1 | Intuition\nThe thought is to compute all the subsets and calculate their ors, store all the ors in a list and return the count of max of that list.\n\n# Approac | LalithSrinandan | NORMAL | 2024-10-18T03:12:57.241591+00:00 | 2024-10-18T03:12:57.241622+00:00 | 81 | false | # Intuition\nThe thought is to compute all the subsets and calculate their ors, store all the ors in a list and return the count of max of that list.\n\n# Approach\nStep1: Use backtracking to compute all the subsets.\nStep2: Or the elements of the subset.\nStep3: Store all the ors in a list.\nStep4: Return the count of max of that list.\n\n# Complexity\n- Time complexity:\nOptimal.\n\n- Space complexity:\nO(n)\n\n# Code\n```java []\nclass Solution {\n public int or(List<Integer> ds){\n int o=ds.get(0);\n for(int i: ds){\n o=o|i;\n }\n return o;\n }\n public void back(int[] nums, List<Integer> ans, List<Integer> ds, int ind){\n if(ind==nums.length){\n if(ds.size()==0) return;\n ans.add(or(ds));\n return;\n }\n ds.add(nums[ind]);\n back(nums, ans, ds, ind+1);\n ds.remove(ds.size()-1);\n back(nums, ans, ds, ind+1);\n }\n public int countMaxOrSubsets(int[] nums) {\n List<Integer> ans= new ArrayList<>();\n back(nums, ans, new ArrayList<>(), 0);\n return Collections.frequency(ans, Collections.max(ans));\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
count-number-of-maximum-bitwise-or-subsets | Fastest code with Step-by-Step Breakdown 💯🔥 | fastest-code-with-step-by-step-breakdown-kaaw | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem revolves around finding how many subsets of a given array have a bitwise OR | uk07 | NORMAL | 2024-10-18T02:33:47.814707+00:00 | 2024-10-18T02:33:47.814762+00:00 | 568 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem revolves around finding how many subsets of a given array have a bitwise OR that equals the maximum OR possible for the entire array. The key insight is that we need to determine the maximum OR value of all elements combined and then count the subsets whose OR matches this value. Given the small size of subsets (as it\u2019s bounded by `2^n`), iterating through all subsets and computing the OR for each seemed like a feasible approach.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. First, calculate the maximum OR value (`mx_or`) by performing a bitwise OR on all the elements in the array `nums`. This represents the highest OR value we can get by OR-ing all elements.\n2. Then, iterate over all possible subsets of the array. We can represent each subset using a bitmask, where each bit in the mask represents whether a particular element is included in the subset.\n3. For each subset, compute the OR of the elements present in that subset.\n4. Count how many subsets have a bitwise OR equal to `mx_or`.\n5. Return this count.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is $$O(n \\cdot 2^n)$$, where:\n - There are `2^n` subsets to iterate through.\n - For each subset, we compute the OR of at most `n` elements.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is $$O(1)$$, excluding the input array `nums` and considering only the space used for a few integer variables. If we consider the input array, the space complexity is $$O(n)$$.\n\n# Code Breakdown\n<!-- Describe your code to solving the problem. -->\n- **Step 1:** Calculate the maximum OR value `mx_or` of all elements in `nums`. This serves as the target OR value that we want to match with different subsets.\n- **Step 2:** Compute the total number of non-empty subsets, which is `2^n - 1`.\n- **Step 3:** Loop through all possible subsets represented by binary masks (from `1` to `2^n - 1`), where each bit in the mask indicates if a number is included in the subset.\n- **Step 4:** For each subset, compute the OR value of the numbers in that subset.\n- **Step 5:** If the OR value of a subset matches `mx_or`, increment the count.\n- **Step 6:** Return the count of subsets that meet the condition.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int mx_or = 0, n = nums.size();\n for(int x: nums) mx_or |= x;\n \n int total_subsets = pow(2, n)-1;\n \n int cnt = 1;\n for(int i=1;i<total_subsets; i++) {\n int or_sub = 0;\n for(int j=0;j<n;j++) {\n int x = 1<<j;\n if(x&i) or_sub |= nums[j];\n }\n if(or_sub==mx_or) ++cnt;\n }\n\n return cnt;\n }\n};\n```\n```java []\nclass Solution {\n public int countMaxOrSubsets(int[] nums) {\n int mx_or = 0;\n int n = nums.length;\n \n for (int x : nums) mx_or |= x;\n \n int total_subsets = (1 << n) - 1;\n \n int cnt = 1;\n for (int i = 1; i <= total_subsets; i++) {\n int or_sub = 0;\n for (int j = 0; j < n; j++) {\n if ((i & (1 << j)) != 0) {\n or_sub |= nums[j];\n }\n }\n if (or_sub == mx_or) cnt++;\n }\n \n return cnt;\n }\n}\n```\n```python []\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n mx_or = 0\n n = len(nums)\n \n for x in nums:\n mx_or |= x\n \n total_subsets = (1 << n) - 1\n \n cnt = 1\n for i in range(1, total_subsets + 1):\n or_sub = 0\n for j in range(n):\n if i & (1 << j):\n or_sub |= nums[j]\n if or_sub == mx_or:\n cnt += 1\n \n return cnt\n\n```\n```golang []\nfunc countMaxOrSubsets(nums []int) int {\n mx_or := 0\n n := len(nums)\n \n for _, x := range nums {\n mx_or |= x\n }\n \n total_subsets := (1 << n) - 1\n cnt := 1\n \n for i := 1; i <= total_subsets; i++ {\n or_sub := 0\n for j := 0; j < n; j++ {\n if i & (1 << j) != 0 {\n or_sub |= nums[j]\n }\n }\n if or_sub == mx_or {\n cnt++\n }\n }\n \n return cnt\n}\n```\n```Rust []\nimpl Solution {\n pub fn count_max_or_subsets(nums: Vec<i32>) -> i32 {\n let mut mx_or = 0;\n let n = nums.len();\n \n for &x in &nums {\n mx_or |= x;\n }\n \n let total_subsets = (1 << n) - 1;\n let mut cnt = 1;\n \n for i in 1..=total_subsets {\n let mut or_sub = 0;\n for j in 0..n {\n if i & (1 << j) != 0 {\n or_sub |= nums[j];\n }\n }\n if or_sub == mx_or {\n cnt += 1;\n }\n }\n \n cnt\n }\n}\n``` | 3 | 1 | ['Array', 'Bit Manipulation', 'Enumeration', 'Python', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript'] | 1 |
count-number-of-maximum-bitwise-or-subsets | Got the job done with hashmap(defaultdict) | 100% efficiency with proof | Python solution | got-the-job-done-with-hashmapdefaultdict-n0nc | \n\n\n# Code\nPython []\nclass Solution(object):\n def countMaxOrSubsets(self, nums):\n hashmap = defaultdict(int)\n for i in nums:\n | Hamza_the_codar_786 | NORMAL | 2024-07-10T07:50:54.161993+00:00 | 2024-07-10T07:50:54.162026+00:00 | 34 | false | \n\n\n# Code\n``` Python []\nclass Solution(object):\n def countMaxOrSubsets(self, nums):\n hashmap = defaultdict(int)\n for i in nums:\n temp = dict(hashmap)\n for j in temp:\n hashmap[j|i] += temp[j]\n hashmap[i] += 1\n \n return hashmap[max(hashmap.keys())]\n```\n\n | 3 | 0 | ['Array', 'Backtracking', 'Bit Manipulation', 'Python'] | 0 |
count-number-of-maximum-bitwise-or-subsets | BRUTER-FORCE || 2^n SOLUTION || C++ || EASY TO UNDERSTAND | bruter-force-2n-solution-c-easy-to-under-b3u6 | \nclass Solution {\npublic:\n int x = 0;\n void solve(int s,int k,int &ans,vector<int> &nums){\n if(s>=nums.size()){\n if(k==x)\n | yash___sharma_ | NORMAL | 2023-03-28T12:57:43.296193+00:00 | 2023-03-28T12:57:43.296240+00:00 | 865 | false | ````\nclass Solution {\npublic:\n int x = 0;\n void solve(int s,int k,int &ans,vector<int> &nums){\n if(s>=nums.size()){\n if(k==x)\n ans++;\n return;\n }\n solve(s+1,k|nums[s],ans,nums);\n solve(s+1,k,ans,nums);\n }\n int countMaxOrSubsets(vector<int>& nums) {\n int ans = 0;\n x = 0;\n for(auto &i: nums)x |= i;\n solve(0,0,ans,nums);\n return ans;\n }\n};\n```` | 3 | 0 | ['Recursion', 'C', 'Bitmask', 'C++'] | 0 |
count-number-of-maximum-bitwise-or-subsets | C++ | Backtracking | c-backtracking-by-sosuke23-ph4p | Code\n\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int reach=0,res=0;\n for(auto x:nums){\n reach|=x;\ | Sosuke23 | NORMAL | 2023-03-17T10:43:10.446058+00:00 | 2023-03-17T10:43:10.446093+00:00 | 302 | false | # Code\n```\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int reach=0,res=0;\n for(auto x:nums){\n reach|=x;\n }\n auto Solve=[&](auto Solve,int ind,int val){\n if(val>67108864){\n return ;\n }\n if(val==reach){\n res++;\n }\n for(int i=ind;i<(int)nums.size();i++){\n Solve(Solve,i+1,val|nums[i]);\n }\n };\n Solve(Solve,0,0);\n return res;\n }\n};\n``` | 3 | 0 | ['Backtracking', 'C++'] | 0 |
count-number-of-maximum-bitwise-or-subsets | C++ | 2 solution | Backtracking + DP Soln | c-2-solution-backtracking-dp-soln-by-ita-kgq9 | Backtracking Soln\n\n\tint res = 0;\n void back(vector<int>nums, int a, int idx, int curr) {\n if(curr==a) res+=1;\n for(int i=idx; i<nums.size | itachi_sks | NORMAL | 2022-01-19T05:38:09.626944+00:00 | 2022-01-20T09:39:03.626655+00:00 | 261 | false | # Backtracking Soln\n```\n\tint res = 0;\n void back(vector<int>nums, int a, int idx, int curr) {\n if(curr==a) res+=1;\n for(int i=idx; i<nums.size(); i++) {\n back(nums, a, i+1, curr|nums[i]);\n }\n }\n int countMaxOrSubsets(vector<int>& nums) {\n long long a = nums[0];\n for(int i=1; i<nums.size(); i++) a |= nums[i];\n back(nums, a, 0, 0);\n return res;\n }\n```\n\n# DP Soln\n```\n\tint countMaxOrSubsets(vector<int>& A) {\n int max = 0;\n\t\tint dp[1 << 17] = {1};\n for (int a: A) {\n for (int i = max; i >= 0; --i)\n dp[i | a] += dp[i];\n max |= a;\n }\n return dp[max];\n }\n``` | 3 | 0 | ['Math', 'Backtracking', 'C'] | 0 |
count-number-of-maximum-bitwise-or-subsets | Python3 Solution | python3-solution-by-satyam2001-40gs | \nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n \n def dfs(i,val):\n if maxBit == val : return 1<<(len(nu | satyam2001 | NORMAL | 2021-11-13T15:04:57.860102+00:00 | 2021-11-13T15:04:57.860140+00:00 | 631 | false | ```\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n \n def dfs(i,val):\n if maxBit == val : return 1<<(len(nums)-i)\n if i == len(nums): return 0\n return dfs(i+1,val|nums[i]) + dfs(i+1,val)\n maxBit = 0\n for i in nums: maxBit |= i\n return dfs(0,0)\n``` | 3 | 0 | ['Backtracking', 'Python', 'Python3'] | 0 |
count-number-of-maximum-bitwise-or-subsets | C++ Simple and Short Solution, No Recursion, Faster than 100% | c-simple-and-short-solution-no-recursion-p08u | Very similar to https://leetcode.com/problems/subsets/discuss/1333022/C%2B%2B-Simple-and-Short-Solution-No-Recursion-0-ms-Faster-than-100\n\nclass Solution {\np | yehudisk | NORMAL | 2021-10-17T13:15:06.339306+00:00 | 2021-10-17T13:15:06.339338+00:00 | 141 | false | Very similar to https://leetcode.com/problems/subsets/discuss/1333022/C%2B%2B-Simple-and-Short-Solution-No-Recursion-0-ms-Faster-than-100\n```\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int res = 0, mx_or = 0, curr, sz;\n vector<int> ors = {0};\n \n for (auto n : nums) mx_or |= n;\n \n for (auto num : nums) {\n sz = ors.size();\n \n for (int i = 0; i < sz; i++) {\n curr = ors[i] | num;\n ors.push_back(curr);\n if (curr == mx_or) res++;\n }\n }\n \n return res;\n }\n};\n```\n**Like it? please upvote!** | 3 | 1 | ['C', 'Iterator'] | 0 |
count-number-of-maximum-bitwise-or-subsets | C++ Failed Approach + Working One | c-failed-approach-working-one-by-abhi_ve-n86p | Code is correct but time complexity is high so below approach failed at last test case :(\nHere we are generating every possible sub array and doing its OR in b | abhi_vee | NORMAL | 2021-10-17T04:27:59.418257+00:00 | 2021-10-17T04:29:43.818874+00:00 | 292 | false | Code is correct but time complexity is high so below approach failed at last test case :(\nHere we are generating every possible sub array and doing its OR in base condition.\n```\nclass Solution {\npublic:\n int res=0, ans=INT_MIN;\n void solve(vector<int> input, vector<int> output)\n {\n if(input.size() == 0)\n {\n if(output.size() != 0)\n {\n int temp_ans = output[0];\n for(int i=0; i<output.size(); i++) \n temp_ans = (temp_ans|output[i]); \n if(temp_ans == ans)\n res++;\n if(temp_ans > ans)\n ans = temp_ans;\n }\n return;\n }\n \n vector<int>op1 = output, op2 = output;\n op1.push_back(input[0]);\n input.erase(input.begin() + 0);\n solve(input, op1);\n solve(input, op2);\n }\n int countMaxOrSubsets(vector<int>& arr) \n {\n solve(arr, {});\n return res+1;\n }\n};\n```\nWorking Approach :\nDoing the OR of entire array first that gives maximum OR and backtracking the array to check current OR == maximum OR\n```\nclass Solution {\n public:\n\tint res = 0;\n\tvoid solve(vector<int> &nums, int ind, int max, int curr)\n\t{\n\t\tif(ind == nums.size())\n\t\t{\n\t\t\tif(curr == max)\n\t\t\t\tres++;\n\t\t\treturn;\n\t\t}\n\t\tsolve(nums, ind+1, max,curr);\n\t\tsolve(nums, ind+1, max, curr|nums[ind]);\n\t}\n\t\n int countMaxOrSubsets(vector<int> arr) \n { \n \tint max=0;\n for(int i=0; i<arr.size(); i++)\n \t\tmax = max|arr[i];\n \tsolve(arr, 0, max, 0);\n \treturn res;\n }\n};\n```\n**Upvote if you like it** | 3 | 0 | ['Backtracking', 'C', 'C++'] | 1 |
count-number-of-maximum-bitwise-or-subsets | C++ bitmask solution. brute-force. | c-bitmask-solution-brute-force-by-chejia-j50v | \n\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int n = nums.size();\n int all = 1 << n;\n int ans = 0;\n | chejianchao | NORMAL | 2021-10-17T04:00:40.696357+00:00 | 2021-10-17T04:00:40.696395+00:00 | 173 | false | \n```\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int n = nums.size();\n int all = 1 << n;\n int ans = 0;\n int mx = 0;\n for(int i = 1; i < all; i++) {\n int val = 0;\n for(int j = 0; j < n; j++) {\n if((1 << j) & i) {\n val |= nums[j];\n }\n }\n if(val >= mx) {\n if(val == mx) {\n ++ans;\n } else {\n ans = 1;\n mx = val;\n }\n }\n }\n return ans;\n }\n};\n``` | 3 | 2 | [] | 0 |
count-number-of-maximum-bitwise-or-subsets | 🔥Lollipop BEATS 💯 % 🎯 |✨SUPER EASY BEGINNERS 👏 | lollipop-beats-super-easy-beginners-by-c-v5ue | \n\n\n---\n\n## Intuition\nThe problem is about finding how many subsets of a list of integers have a bitwise OR equal to the maximum possible bitwise OR of the | CodeWithSparsh | NORMAL | 2024-10-21T16:03:07.802941+00:00 | 2024-10-21T16:10:18.742230+00:00 | 19 | false | \n\n\n---\n\n## Intuition\nThe problem is about finding how many subsets of a list of integers have a bitwise OR equal to the maximum possible bitwise OR of the entire list. The maximum bitwise OR is achieved by taking the OR of all the numbers in the list. To count the subsets, we can use a recursive approach that explores every possible subset, either including or excluding each number in the list.\n\n## Approach\n1. **Calculate the Maximum OR Value:** First, we calculate the bitwise OR of all the elements in the list, which gives us the maximum OR value.\n2. **Recursive Subset Exploration:** We use a recursive function to explore each subset of the list. For each element, we have two choices: include it in the subset or exclude it. We keep track of the current OR value of the subset as we explore.\n3. **Count Subsets:** If the current subset\'s OR value matches the maximum OR value, we count that subset.\n\n## Complexity\n- **Time complexity:** $$O(2^n)$$ since there are $$2^n$$ subsets of a list with \\(n\\) elements.\n- **Space complexity:** $$O(n)$$ due to the recursion stack.\n\n```dart []\nclass Solution {\n int countMaxOrSubsets(List<int> nums) {\n int maxM = 0;\n for (int n in nums) maxM |= n; // Calculate maximum OR\n return recurse(maxM, 0, nums);\n }\n\n int recurse(int maxM, int currentBit, List<int> nums) {\n if (nums.isEmpty) {\n return currentBit == maxM ? 1 : 0; // Check if OR matches maxM\n }\n\n // Explore subsets including or excluding the first element\n int include = recurse(maxM, currentBit | nums.first, nums.sublist(1));\n int exclude = recurse(maxM, currentBit, nums.sublist(1));\n return include + exclude;\n }\n}\n```\n\n```python []\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n max_or = 0\n for num in nums:\n max_or |= num # Calculate maximum OR\n \n def backtrack(idx, current_or):\n if idx == len(nums):\n return 1 if current_or == max_or else 0\n \n # Subsets including or excluding the current element\n return (backtrack(idx + 1, current_or | nums[idx]) +\n backtrack(idx + 1, current_or))\n \n return backtrack(0, 0)\n```\n\n```cpp []\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int maxOr = 0;\n for (int num : nums) maxOr |= num; // Calculate maximum OR\n return recurse(maxOr, 0, 0, nums);\n }\n \n int recurse(int maxOr, int idx, int currentOr, vector<int>& nums) {\n if (idx == nums.size()) {\n return currentOr == maxOr ? 1 : 0;\n }\n\n // Subsets including or excluding the current element\n return recurse(maxOr, idx + 1, currentOr | nums[idx], nums) +\n recurse(maxOr, idx + 1, currentOr, nums);\n }\n};\n```\n\n```java []\nclass Solution {\n public int countMaxOrSubsets(int[] nums) {\n int maxOr = 0;\n for (int num : nums) maxOr |= num; // Calculate maximum OR\n return recurse(maxOr, 0, 0, nums);\n }\n\n private int recurse(int maxOr, int idx, int currentOr, int[] nums) {\n if (idx == nums.length) {\n return currentOr == maxOr ? 1 : 0;\n }\n\n // Subsets including or excluding the current element\n return recurse(maxOr, idx + 1, currentOr | nums[idx], nums) +\n recurse(maxOr, idx + 1, currentOr, nums);\n }\n}\n```\n\n```javascript []\nvar countMaxOrSubsets = function(nums) {\n let maxOr = 0;\n for (let num of nums) maxOr |= num; // Calculate maximum OR\n\n const recurse = (idx, currentOr) => {\n if (idx === nums.length) return currentOr === maxOr ? 1 : 0;\n\n // Subsets including or excluding the current element\n return recurse(idx + 1, currentOr | nums[idx]) +\n recurse(idx + 1, currentOr);\n };\n\n return recurse(0, 0);\n};\n```\n\n```go []\npackage main\n\nfunc countMaxOrSubsets(nums []int) int {\n maxOr := 0\n for _, num := range nums {\n maxOr |= num // Calculate maximum OR\n }\n return recurse(maxOr, 0, 0, nums)\n}\n\nfunc recurse(maxOr, idx, currentOr int, nums []int) int {\n if idx == len(nums) {\n if currentOr == maxOr {\n return 1\n }\n return 0\n }\n\n // Subsets including or excluding the current element\n return recurse(maxOr, idx + 1, currentOr | nums[idx], nums) +\n recurse(maxOr, idx + 1, currentOr, nums)\n}\n```\n\n---\n\n {:style=\'width:250px\'} | 2 | 0 | ['Bit Manipulation', 'Recursion', 'C', 'C++', 'Java', 'Go', 'Python3', 'JavaScript', 'Dart'] | 1 |
count-number-of-maximum-bitwise-or-subsets | 🚀Completed in 14ms: Beats 100%!🚀 | completed-in-14ms-beats-100-by-dddurnov-94qx | \n\n\n\n# Complexity\n- Time complexity: O(2^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 | dddurnov | NORMAL | 2024-10-18T16:21:15.352476+00:00 | 2024-10-18T16:21:15.352526+00:00 | 32 | false | \n\n\n\n# Complexity\n- Time complexity: $$O(2^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```javascript []\nfunction countMaxOrSubsets(nums) {\n const maxOr = nums.reduce((acc, cur) => acc | cur, 0);\n let count = 0;\n\n function backtrack(start, currentOr) {\n if (currentOr === maxOr) {\n count++;\n }\n\n for (let i = start; i < nums.length; i++) {\n backtrack(i + 1, currentOr | nums[i]);\n }\n }\n\n backtrack(0, 0);\n return count;\n}\n```\n```typescript []\nfunction countMaxOrSubsets(nums: number[]): number {\n const maxOr = nums.reduce((acc, cur) => acc | cur, 0);\n let count = 0;\n\n function backtrack(start: number, currentOr: number) {\n if (currentOr === maxOr) {\n count++;\n }\n\n for (let i = start; i < nums.length; i++) {\n backtrack(i + 1, currentOr | nums[i]);\n }\n }\n\n backtrack(0, 0);\n return count;\n}\n```\n | 2 | 0 | ['Array', 'Backtracking', 'Bit Manipulation', 'Enumeration', 'TypeScript', 'JavaScript'] | 0 |
count-number-of-maximum-bitwise-or-subsets | Beats 100% || Clean code using Counter in python | beats-100-clean-code-using-counter-in-py-8ynd | 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 | anand_shukla1312 | NORMAL | 2024-10-18T13:45:45.559174+00:00 | 2024-10-18T13:45:45.559209+00:00 | 27 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n max_or = 0\n prev = Counter()\n prev[0] = 1\n \n for elem in nums:\n max_or |= elem\n\n current = Counter()\n for prev_or, cnt in prev.items():\n current[prev_or | elem] += cnt\n prev.update(current)\n \n return prev[max_or]\n\n``` | 2 | 0 | ['Python3'] | 0 |
count-number-of-maximum-bitwise-or-subsets | easy take not take solution | easy-take-not-take-solution-by-batch89-mav6 | 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 | batch89 | NORMAL | 2024-10-18T13:27:52.906099+00:00 | 2024-10-18T13:27:52.906136+00:00 | 13 | 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 orsum = 0;\n int n;\n int solve(int i, int sum, vector<int>&nums)\n {\n if(i==n)\n {\n if(sum == orsum)\n {\n return 1;\n }\n return 0;\n }\n int take = solve(i+1, sum|nums[i], nums);\n int not_take = solve(i+1,sum, nums);\n return take + not_take;\n }\n int countMaxOrSubsets(vector<int>& nums) \n {\n n = nums.size();\n for(auto val: nums)\n {\n orsum = orsum | val;\n }\n return solve(0,0,nums);\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
count-number-of-maximum-bitwise-or-subsets | Simple & Easy Solution with step by step explanation | simple-easy-solution-with-step-by-step-e-bb1z | Approach\n- Step 1: Find the maximum possible OR of the entire array. This value is the OR of all elements combined, as it represents the upper bound of any sub | yash_visavadia | NORMAL | 2024-10-18T13:15:26.038452+00:00 | 2024-10-18T13:15:26.038477+00:00 | 10 | false | # Approach\n- **Step 1:** Find the maximum possible OR of the entire array. This value is the OR of all elements combined, as it represents the upper bound of any subset OR.\n\n- **Step 2:** Iterate through all possible subsets of the array (using itertools.combinations) and calculate the OR of each subset. Count how many subsets have an OR equal to the maximum OR.\n\n# Explanation\n\n1. max_or_from_array(nums): This helper function computes the bitwise OR for any given array (or subset).\n - We initialize max_or to 0 and perform a bitwise OR with each number in the array.\n\n2. countMaxOrSubsets(nums): This function calculates the number of subsets whose OR is equal to the maximum OR.\n\n - We first calculate the maximum OR of the full array.\n\n - Using itertools.combinations, we generate all subsets, compute their OR, and count how many of them match the maximum OR.\n\n# Complexity\nTime complexity is `O(n * 2 ^ n)` where `n` is the length of `nums`. This is because we generate `2 ^ n` subsets, and for each subset, we calculate the OR, which takes `O(n)`.\n\n# Code\n```python3 []\nfrom itertools import combinations\n\n\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n cnt = 0\n max_or = max_or_from_array(nums)\n\n for i in range(1, len(nums) + 1):\n for combination in combinations(nums, i):\n if max_or_from_array(combination) == max_or:\n cnt += 1\n\n return cnt\n\n\ndef max_or_from_array(nums):\n max_or = 0\n\n for num in nums:\n max_or |= num\n\n return max_or\n``` | 2 | 0 | ['Python3'] | 0 |
count-number-of-maximum-bitwise-or-subsets | [Swift] 1-liner, combinations(ofCount:) | swift-1-liner-combinationsofcount-by-iam-syhj | \n\n# Code\nswift []\nimport Algorithms\n\nclass Solution {\n func countMaxOrSubsets(_ nums: [Int]) -> Int {\n nums\n .combinations(ofCount: 1. | iamhands0me | NORMAL | 2024-10-18T11:13:26.974883+00:00 | 2024-10-18T11:13:56.219218+00:00 | 26 | false | \n\n# Code\n```swift []\nimport Algorithms\n\nclass Solution {\n func countMaxOrSubsets(_ nums: [Int]) -> Int {\n nums\n .combinations(ofCount: 1...)\n .map { $0.reduce(into: 0) { $0 = $0 | $1 } }\n .reduce(into: [:]) { $0[$1, default: 0] += 1 }\n .max { $0.key < $1.key }?.value ?? 0\n }\n}\n``` | 2 | 0 | ['Swift'] | 1 |
count-number-of-maximum-bitwise-or-subsets | Beginner friendly- two approach ✅ ✅ | beginner-friendly-two-approach-by-shasha-uo3s | Intuition\nThe goal is to find the maximum possible bitwise OR of any subset of the array nums and count how many subsets achieve this maximum OR.\n\n# Approach | shashankgpt07 | NORMAL | 2024-10-18T09:05:18.325449+00:00 | 2024-10-18T09:05:18.325469+00:00 | 80 | false | # Intuition\nThe goal is to find the maximum possible bitwise OR of any subset of the array nums and count how many subsets achieve this maximum OR.\n\n# Approach\n1. **Calculate Maximum OR**: The maximum OR is achieved by ORing all elements together. This gives the maximum OR any subset can achieve.\n\n2. **Count Subsets with Maximum OR**: We use recursion (backtracking) to explore all subsets:\n\n- **Include or exclude each element**: Recursively OR the current element with the running OR result or skip it.\n- **Check base case**: When all elements are considered, if the OR of the subset matches the maximum OR, increment the count.\n\n# Complexity\n- **Time complexity**: $$O(2^n)$$ where `n` is the size of the array nums. This is because we are generating all subsets of the array.\n\n\n- **Space complexity**:\n$$O(n)$$ for the recursion stack.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n void solve(int& count, int idx, vector<int>& nums, int temp, int& maxOr) {\n\n if (idx == nums.size()) {\n if (temp == maxOr) {\n count = count + 1;\n }\n return;\n }\n solve(count, idx + 1, nums, temp, maxOr); // Exclude current element\n solve(count, idx + 1, nums, temp | nums[idx], maxOr); // Include current element\n }\n int countMaxOrSubsets(vector<int>& nums) {\n int maxOr = 0;\n for (auto i : nums) {\n maxOr = maxOr | i;\n }\n int count = 0;\n int temp = 0;\n solve(count, 0, nums, temp, maxOr);\n return count;\n }\n};\n``` | 2 | 0 | ['Array', 'Bit Manipulation', 'Recursion', 'Enumeration', 'C++'] | 0 |
count-number-of-maximum-bitwise-or-subsets | 100% beat | Simple Approach | Recursion | 100-beat-simple-approach-recursion-by-ay-7ujp | 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 | Ayush6944 | NORMAL | 2024-10-18T07:01:24.416923+00:00 | 2024-10-18T07:01:24.416952+00:00 | 173 | 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[]} nums\n * @return {number}\n */\nvar countMaxOrSubsets = function(nums) {\n function countSubset(idx,currOr,nums,maxOr){\n //base case\n if(idx == nums.length){\n //out of bound \n if(currOr === maxOr){\n return 1\n }\n return 0\n }\n let takeCount = countSubset(idx+1,currOr | nums[idx],nums,maxOr)\n let nottake = countSubset(idx+1,currOr,nums,maxOr)\n return takeCount + nottake\n }\n let maxOr = 0\n for(let i of nums){\n //calculate all element\'s OR \n maxOr |=i\n }\n let currOr = 0\n return countSubset(0,currOr ,nums,maxOr)\n};\n``` | 2 | 0 | ['Array', 'Backtracking', 'Bit Manipulation', 'Python3', 'JavaScript'] | 0 |
count-number-of-maximum-bitwise-or-subsets | Take or Not Take ✅ || [C++] 🚀 || Easy step by step 💯 | take-or-not-take-c-easy-step-by-step-by-9e8qn | \nclass Solution {\nint ans = 0;\nprivate:\n int helpXOR(vector<int>& temp)\n {\n if (temp.empty()) return 0;\n int count = temp[0];\n | RIOLOG | NORMAL | 2024-10-18T05:29:33.845694+00:00 | 2024-10-18T05:29:33.845714+00:00 | 88 | false | ```\nclass Solution {\nint ans = 0;\nprivate:\n int helpXOR(vector<int>& temp)\n {\n if (temp.empty()) return 0;\n int count = temp[0];\n for (int i=1;i<temp.size();i++) count |= temp[i];\n return count;\n }\n \n void helpmeRec(int ind, vector<int>& nums, int target , vector<int>& temp)\n {\n if (ind >= nums.size())\n {\n int currVal = helpXOR(temp);\n if (target == currVal) ans += 1;\n //if (temp.size() > 0) temp.pop_back();\n return ;\n }\n \n //notTake\n helpmeRec(ind+1, nums, target, temp);\n \n //take\n temp.push_back(nums[ind]);\n helpmeRec(ind+1, nums, target, temp);\n temp.pop_back();\n }\n \npublic:\n int countMaxOrSubsets(vector<int>& nums) \n { \n int maxiXor = 0;\n for (int i=0;i<nums.size();i++) maxiXor |= nums[i];\n \n //cout<<"maxi XOR"<<" "<<maxiXor<<endl;\n \n vector<int>temp;\n \n helpmeRec(0, nums, maxiXor, temp);\n return ans;\n }\n};\n``` | 2 | 0 | ['Backtracking', 'Recursion', 'C++'] | 0 |
count-number-of-maximum-bitwise-or-subsets | JAVA BACKTRACKING SOLUTION || KHANDANI BACKTRACKING TEMPLATE | java-backtracking-solution-khandani-back-4i0h | Intuition\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- Tim | abhinavsinghnegi | NORMAL | 2024-10-18T05:15:27.464083+00:00 | 2024-10-18T05:15:27.464108+00:00 | 219 | false | # Intuition\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n void solve(int[] nums, ArrayList<Integer> temp, int idx, int n, int curror, int maxor, int[] count) {\n // at the end of recursion check if the subsequemce or is equal to maxor \n if (idx>=n&&curror == maxor) {\n count[0]++;\n }\n // if not then it will return \n if (idx >= n) return;\n // backtracking template\n\n // Include current number\n temp.add(nums[idx]);\n solve(nums, temp, idx + 1, n, curror | nums[idx], maxor, count);// do the or of every element on each call \n temp.remove(temp.size() - 1);\n // Exclude current number\n solve(nums, temp, idx + 1, n, curror, maxor, count);\n }\n\n public int countMaxOrSubsets(int[] nums) {\n int n = nums.length;\n ArrayList<Integer> temp = new ArrayList<>();\n int[] count = new int[1]; // Use an array to pass by reference\n int maxor = 0;\n // maxor is the of of whole array \n for (int i : nums) {\n maxor = maxor | i;\n }\n solve(nums, temp, 0, n, 0, maxor, count);\n return count[0];\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
count-number-of-maximum-bitwise-or-subsets | Backtracking solution, very easy to understand | backtracking-solution-very-easy-to-under-293k | Intuition\n Describe your first thoughts on how to solve this problem. \nSince the max length of the array is just 16, we use backtracking to check all possible | aiqqia | NORMAL | 2024-10-18T04:19:06.626134+00:00 | 2024-10-18T04:19:06.626181+00:00 | 39 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince the max length of the array is just 16, we use backtracking to check all possible subsets of this array and if any of the subset\'s OR is the same as the max OR, we add it to the answer. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe know that since OR only increases the value of a variable, the maximum OR will be the OR of the entire array. We start with index 0 and at every index we maintain the current OR. We decide either to ignore or select the current number in the subset. In the end of the array, if the current OR of the subset is equal to the max OR, we just add 1 to our answer. The recursive method helps check all possible subsets by either choosing or ignoring an element at every index.\n\n# Complexity\n- Time complexity: O(2^n) (Since backtracking)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n) (Stack space)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int getSubsets(int[] nums, int index, int maxOr, int curOr){\n if(index == nums.length) \n return maxOr == curOr ? 1: 0;\n int sum = 0;\n sum += getSubsets(nums, index+1, maxOr, (curOr | nums[index]));\n sum += getSubsets(nums, index+1, maxOr, curOr);\n return sum;\n }\n public int countMaxOrSubsets(int[] nums) {\n int maxOr = 0;\n for(int n: nums)\n maxOr = (maxOr | n);\n return getSubsets(nums, 0, maxOr, 0);\n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
count-number-of-maximum-bitwise-or-subsets | #beats 100% #simple recursive solution #Include/Not-Include Pattern | beats-100-simple-recursive-solution-incl-u2zt | Intuition\nThe task requires counting the number of subsets whose bitwise OR value equals the maximum possible bitwise OR that can be obtained from all elements | Adarsh_Gupta_0601 | NORMAL | 2024-10-18T03:22:02.292892+00:00 | 2024-10-18T03:22:02.292924+00:00 | 35 | false | # Intuition\nThe task requires counting the number of subsets whose bitwise OR value equals the maximum possible bitwise OR that can be obtained from all elements in the array. By recursively exploring all possible subsets, we can find how many subsets meet this condition.\n\n# Approach\n1. Calculate Maximum Bitwise OR:\nFirst, compute the maximum possible bitwise OR (maxBitwise) by performing a bitwise OR on all elements of the nums array. This value represents the target we need to match using subsets.\nRecursive Function:\n\n2. Implement a recursive function count to explore all subsets of nums.\nFor each element in nums, we have two choices: either include it in the current subset or exclude it.\nIf the index ind exceeds the size of the array, check if the current subset\'s OR value (bitwise) matches maxBitwise. If so, return 1 (indicating this subset is valid). Otherwise, return 0.\n\n3. Base Case:\nWhen ind >= size, return 1 if the subset\'s OR equals the target (maxBitwise), otherwise return 0.\n\n\n4. For each element, sum the results of including and excluding the element. This allows counting how many subsets match the maxBitwise.\nFinal Result:\n\n5. The result of countMaxOrSubsets is the sum of all recursive calls, representing how many subsets meet the required OR condition.\nComplexity\n\n# Time complexity:\nThe time complexity is O(2^n), where n is the size of the input array. This is because every element can either be included or excluded, leading to 2^n possible subsets.\n\n# Space complexity:\nThe space complexity is O(n) due to the depth of the recursive call stack. In the worst case, the recursion goes as deep as the number of elements in the array.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int count(vector<int>&nums,int target,int ind, int &size,int bitwise){\n if(ind >= size){\n if(bitwise == target)return 1;\n else return 0;\n }\n int ans = 0;\n //take \n ans += count(nums,target,ind+1,size,bitwise|nums[ind]);\n //not take\n ans += count(nums,target,ind+1,size,bitwise);\n return ans;\n }\n int countMaxOrSubsets(vector<int>& nums) {\n int n = nums.size();\n int maxBitwise = 0;\n for(auto &val : nums){\n maxBitwise |= val;\n }\n int ans = count(nums,maxBitwise,0,n,0);\n return ans;\n }\n};\n``` | 2 | 0 | ['Array', 'Backtracking', 'Bit Manipulation', 'Recursion', 'C++'] | 2 |
count-number-of-maximum-bitwise-or-subsets | Java Solution for Count Number of Maximum Bitwise - OR Subsets Problem | java-solution-for-count-number-of-maximu-wuob | Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal is to find the maximum possible bitwise OR of a subset of the given array and | Aman_Raj_Sinha | NORMAL | 2024-10-18T03:08:52.881950+00:00 | 2024-10-18T03:08:52.881985+00:00 | 247 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to find the maximum possible bitwise OR of a subset of the given array and count how many different non-empty subsets can achieve this maximum OR value. Since the bitwise OR operation accumulates values as more elements are added to a subset, the largest OR we can achieve comes from the full array or one of its subsets. The key observation is that subsets can be generated through recursion, and by keeping track of the OR result for each subset, we can count how many subsets give the desired result.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tMax OR Calculation:\n\t\u2022\tFirst, we calculate the maximum bitwise OR possible by performing the OR operation across all elements in the array. This is the maximum OR that any subset can achieve.\n\t\u2022\tThis step is simple because the bitwise OR of the whole array will be the largest OR achievable.\n2.\tSubset Enumeration:\n\t\u2022\tWe recursively generate all possible subsets and compute their bitwise ORs. For each subset, we check if the OR result equals the maximum OR computed earlier.\n\t\u2022\tFor each element in the array, we have two choices: either include it in the subset or exclude it. This gives rise to 2^n possible subsets.\n\t\u2022\tWe use recursion to explore both possibilities (include or exclude) at each step, updating the current OR as we go.\n3.\tCounting Valid Subsets:\n\t\u2022\tIf the OR of the current subset matches the maximum OR, we increment our counter. This recursive approach ensures that we examine every subset of the array.\n4.\tRecursive Helper Function:\n\t\u2022\tThe helper function countSubsetsWithMaxOr is used to recursively calculate the OR of subsets and count how many of them match the maximum OR.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSubset generation: For an array of length n, there are 2^n possible subsets (including both the empty and non-empty subsets). For each subset, we compute the bitwise OR, which takes O(1) time per subset. Thus, the time complexity is O(2^n).\n\u2022\tIn this problem, n is at most 16, so the number of subsets is 2^{16} = 65536, which is feasible within this time complexity.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nRecursive depth: The depth of recursion is equal to the length of the array, so the space complexity of the recursion stack is O(n).\n\u2022\tAuxiliary space: Apart from the recursion stack, no additional data structures with significant space usage are needed.\n\u2022\tThus, the total space complexity is O(n).\n\n# Code\n```java []\nclass Solution {\n public int countMaxOrSubsets(int[] nums) {\n int maxOr = 0;\n for (int num : nums) {\n maxOr |= num;\n }\n\n return countSubsetsWithMaxOr(nums, 0, 0, maxOr);\n }\n\n private int countSubsetsWithMaxOr(int[] nums, int index, int currentOr, int maxOr) {\n if (index == nums.length) {\n return currentOr == maxOr ? 1 : 0;\n }\n int include = countSubsetsWithMaxOr(nums, index + 1, currentOr | nums[index], maxOr);\n int exclude = countSubsetsWithMaxOr(nums, index + 1, currentOr, maxOr);\n return include + exclude;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
count-number-of-maximum-bitwise-or-subsets | ✅ Simple Java Solution | simple-java-solution-by-harsh__005-kyad | CODE\nJava []\nprivate void solve(int[] nums, int i, int n, int xor, int[] res) {\n\tif(i == n) {\n\t\tif(xor == res[0]) res[1]++;\n\t\telse if(xor > res[0]) {\ | Harsh__005 | NORMAL | 2024-10-18T02:55:17.667382+00:00 | 2024-10-18T02:55:17.667426+00:00 | 87 | false | ## **CODE**\n```Java []\nprivate void solve(int[] nums, int i, int n, int xor, int[] res) {\n\tif(i == n) {\n\t\tif(xor == res[0]) res[1]++;\n\t\telse if(xor > res[0]) {\n\t\t\tres[0] = xor;\n\t\t\tres[1] = 1;\n\t\t}\n\t\treturn;\n\t}\n\tsolve(nums, i+1, n, xor|nums[i], res);\n\tsolve(nums, i+1, n, xor, res);\n}\n\npublic int countMaxOrSubsets(int[] nums) {\n\t// res[0] = value, res[1] = count\n\tint[] res = new int[2];\n\tsolve(nums, 0, nums.length, 0, res);\n\treturn res[1];\n}\n``` | 2 | 0 | ['Java'] | 1 |
count-number-of-maximum-bitwise-or-subsets | Rust | 1-liner | rust-1-liner-by-jsusi-36ch | Code\nrust []\nimpl Solution {\n pub fn count_max_or_subsets(nums: Vec<i32>) -> i32 {\n (0..1 << nums.len())\n .fold((0, 0), |(count, max_b | JSusi | NORMAL | 2024-10-18T01:54:25.204683+00:00 | 2024-10-22T15:46:29.994754+00:00 | 53 | false | # Code\n```rust []\nimpl Solution {\n pub fn count_max_or_subsets(nums: Vec<i32>) -> i32 {\n (0..1 << nums.len())\n .fold((0, 0), |(count, max_bo), combo| {\n nums\n .iter()\n .enumerate()\n .filter_map(|(i, num)| ((combo >> i) & 1 == 1).then_some(*num))\n .reduce(|acc, num| acc | num)\n .map_or((count, max_bo), |bo| match bo.cmp(&max_bo) {\n std::cmp::Ordering::Less => (count, max_bo),\n std::cmp::Ordering::Equal => (count + 1, max_bo),\n std::cmp::Ordering::Greater => (1, bo),\n })\n })\n .0\n }\n}\n``` | 2 | 0 | ['Rust'] | 1 |
count-number-of-maximum-bitwise-or-subsets | Rust solution beats 100%, backtracking | rust-solution-beats-100-backtracking-by-qb0v7 | Code\nrust []\nimpl Solution {\n pub fn bt(i: usize, mut v: i32, m: i32, nums: &Vec<i32>) -> i32 {\n if i == nums.len() {\n if v == m { ret | sunjesse | NORMAL | 2024-10-18T00:22:23.213288+00:00 | 2024-10-18T00:22:23.213319+00:00 | 137 | false | # Code\n```rust []\nimpl Solution {\n pub fn bt(i: usize, mut v: i32, m: i32, nums: &Vec<i32>) -> i32 {\n if i == nums.len() {\n if v == m { return 1; }\n return 0;\n }\n Self::bt(i+1, v | nums[i], m, nums) + Self::bt(i+1, v, m, nums)\n }\n\n pub fn count_max_or_subsets(nums: Vec<i32>) -> i32 {\n let m: i32 = nums.iter().fold(0, |acc, v| acc | v);\n Self::bt(0, 0, m, &nums)\n }\n}\n``` | 2 | 0 | ['Rust'] | 3 |
count-number-of-maximum-bitwise-or-subsets | Simple python3 solution | 11 ms - faster than 100.00% solutions | simple-python3-solution-11-ms-faster-tha-za89 | Complexity\n- Time complexity: O(n \cdot 2^n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(2^n)\n Add your space complexity here, e.g. O | tigprog | NORMAL | 2024-01-16T11:40:37.355137+00:00 | 2024-10-18T00:11:34.247635+00:00 | 148 | false | # Complexity\n- Time complexity: $$O(n \\cdot 2^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(2^n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n max_or = 0\n prev = Counter()\n prev[0] = 1\n \n for elem in nums:\n max_or |= elem\n\n current = Counter()\n for prev_or, cnt in prev.items():\n current[prev_or | elem] += cnt\n prev.update(current)\n \n return prev[max_or]\n``` | 2 | 0 | ['Dynamic Programming', 'Bit Manipulation', 'Python3'] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.