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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
shortest-distance-to-a-character | best approach JS | best-approach-js-by-javad_pk-yrvk | 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 | javad_pk | NORMAL | 2024-05-23T19:07:51.736847+00:00 | 2024-05-23T19:28:01.462363+00:00 | 407 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {string} s\n * @param {character} c\n * @return {number[]}\n */\nvar shortestToChar = function(s, c) {\n let ind=[]\n let res=[]\n for(let i=0;i<s.length;i++){\n if(s[i]==c) ind.push(i)\n }\n for(let i=0;i<s.length;i++){\n let t=s.length\n for(let x of ind) t=Math.min(Math.abs(i-x),t);\n res.push(t)\n }\n return res\n};\n``` | 2 | 0 | ['JavaScript'] | 1 |
shortest-distance-to-a-character | Easy java solution with explanation ✅🚀🎯 | easy-java-solution-with-explanation-by-v-b7o7 | Intuition\nThe problem requires finding the shortest distance from each character in the string to a given character \'c\'. We can observe that the shortest dis | vidojevica | NORMAL | 2024-04-19T21:35:55.397467+00:00 | 2024-04-19T21:35:55.397490+00:00 | 971 | false | # Intuition\nThe problem requires finding the shortest distance from each character in the string to a given character \'c\'. We can observe that the shortest distance to \'c\' for any character is the minimum of the distances to \'c\' on its left and right sides.\n\n# Approach\n1. First, we find all positions of character \'c\' in the string and store them in a list.\n2. Then, we iterate through the string and for each character:\n - If the character is \'c\', we set the distance to 0 and move to the next position of \'c\'.\n - If the character is not \'c\', we calculate its distance to the nearest \'c\' using the positions we found earlier.\n3. We return the resulting array.\n\n\n# Complexity\n- Time complexity:\n - Finding positions of character \'c\' takes O(n).\n - Iterating through the string takes O(n).\n - Overall time complexity is O(n).\n\n\n- Space complexity:\n - Storing positions of character \'c\' takes O(n).\nThe resulting array takes O(n).\nOverall space complexity is O(n).\n\n# Code\n```\nclass Solution {\n public int[] shortestToChar(String s, char c) \n {\n int[] result = new int[s.length()];\n List<Integer> cPositions = new ArrayList<>();\n\n int currPos = 0;\n\n for (int i = 0; i < s.length(); i++)\n {\n if (s.charAt(i) == c) cPositions.add(i);\n }\n\n int k = 0;\n for (int i = 0; i < s.length(); i++)\n {\n \tif (currPos == cPositions.size())\n {\n \tresult[k++] = i - cPositions.get(currPos - 1);\n }\n \telse\n \t{\n \t\tint p = cPositions.get(currPos);\n\n if (i == p) \n {\n result[k++] = 0;\n currPos++;\n }\n else if (currPos == 0) result[k++] = p - i;\n else\n {\n int p2 = cPositions.get(currPos - 1);\n result[k++] = Math.min(i - p2, p - i);\n } \n \t} \n }\n\n return result;\n }\n}\n``` | 2 | 0 | ['Array', 'String', 'Java'] | 0 |
shortest-distance-to-a-character | Go O(N) | go-on-by-aspic-xpyz | \n# Code\n\nfunc shortestToChar(s string, c byte) []int {\n\twalkLeftToRight, cPos := make([]int, len(s)), -len(s)\n\tfor i := range s {\n\t\tif s[i] == c {\n\t | aspic | NORMAL | 2023-12-19T08:16:00.212409+00:00 | 2023-12-19T08:16:00.212430+00:00 | 135 | false | \n# Code\n```\nfunc shortestToChar(s string, c byte) []int {\n\twalkLeftToRight, cPos := make([]int, len(s)), -len(s)\n\tfor i := range s {\n\t\tif s[i] == c {\n\t\t\tcPos = i\n\t\t} else {\n\t\t\twalkLeftToRight[i] = i - cPos\n\t\t}\n\t}\n\tfor r := len(s) - 1; r >= 0; r-- {\n\t\tif s[r] == c {\n\t\t\tcPos = r\n\t\t} else {\n\t\t\twalkLeftToRight[r] = minNum(walkLeftToRight[r], int(math.Abs(float64(cPos)-float64(r))))\n\t\t}\n\t}\n\treturn walkLeftToRight\n}\n\nfunc minNum(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n``` | 2 | 0 | ['Go'] | 0 |
shortest-distance-to-a-character | explain with step wise dry run ... | explain-with-step-wise-dry-run-by-anshik-z81x | \n\n# Approach\nStep 1: Finding the positions of character \'e\' in the string \'loveleetcode\'\nThe positions of \'e\' are: [3, 5, 6, 11]\nStep 2: Calculating | Anshika_73_ | NORMAL | 2023-12-02T08:35:20.256869+00:00 | 2023-12-02T08:35:20.256896+00:00 | 417 | false | \n\n# Approach\nStep 1: Finding the positions of character \'e\' in the string \'loveleetcode\'\nThe positions of \'e\' are: [3, 5, 6, 11]\nStep 2: Calculating the distance from each character to the nearest occurrence of \'e\'\nFor each character in the string, calculate the minimum distance to any of the positions obtained in Step 1.\ni\tCharacter\tDistances to \'e\' Positions\tMinimum Distance\n0\tl\t[3, 5, 6, 11]\t3\n1\to\t[2, 4, 5, 10]\t2\n2\tv\t[1, 3, 4, 9]\t1\n3\te\t[0, 2, 3, 8]\t0\n4\tl\t[3, 5, 6, 11]\t3\n5\te\t[0, 2, 3, 8]\t0\n6\te\t[0, 2, 3, 8]\t0\n7\tt\t[1, 3, 4, 9]\t1\n8\tc\t[2, 4, 5, 10]\t2\n9\to\t[2, 4, 5, 10]\t2\n10\td\t[1, 3, 4, 9]\t1\n11\te\t[0, 2, 3, 8]\t0\nOutput:\nThe final result is a vector of distances from each character to the nearest occurrence of the target character \'e\': [3, 2, 1, 0, 3, 0, 0, 1, 2, 2, 1, 0].\n\n\n\n\n\n\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int>position;\n vector<int>ans;\n for(int i=0;i<s.length();i++){\n if(s[i]==c){\n position.push_back(i);\n }\n }\n //left\n for(int i=0;i<s.length();i++){ \n int m=INT_MAX;\n //right\n for(int j=0;j<position.size();j++){\n m=min(m,abs(i-position[j]));\n }\n ans.push_back(m);\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
shortest-distance-to-a-character | Python | Easy | Array | Shortest Distance to a Character | python-easy-array-shortest-distance-to-a-wcg4 | \nsee the Successfully Accepted Submission\nPython\nclass Solution(object):\n def shortestToChar(self, s, c):\n """\n :type s: str\n :ty | Khosiyat | NORMAL | 2023-10-05T14:55:06.195051+00:00 | 2023-10-05T14:55:06.195069+00:00 | 514 | false | \n[see the Successfully Accepted Submission](https://leetcode.com/submissions/detail/940703040/)\n```Python\nclass Solution(object):\n def shortestToChar(self, s, c):\n """\n :type s: str\n :type c: str\n :rtype: List[int]\n """ \n lengthOf_string = len(s)\n result = [lengthOf_string] * lengthOf_string\n lastItem_string = -lengthOf_string\n for i in list(range(lengthOf_string)) + list(range(lengthOf_string)[::-1]):\n if(s[i] == c): lastItem_string = i\n result[i] = min(result[i], abs(i - lastItem_string))\n return result \n```\n\n**Intuituin**\n \nDefine a method named shortestToChar that takes two arguments:\n- ` \'s\' `: The input string.\n- ` \'c\' `: The character to which distances are calculated.\n- The method returns a list of integers representing the shortest distances.\n```\n def shortestToChar(self, s, c):\n```\nGet the length of the input string \'s\'.\n```\n lengthOf_string = len(s)\n```\nCreate a list \'result\' of length \'lengthOf_string\' filled with maximum possible distances (initialization).\n```\n result = [lengthOf_string] * lengthOf_string\n```\nInitialize a variable \'lastItem_string\' to -lengthOf_string. This variable keeps track of the last occurrence of \'c\'.\n```\n lastItem_string = -lengthOf_string\n```\n- Iterate through the indices of \'s\' in ascending order and then in descending order.\n- This covers both left and right directions from each character.\n```\n for i in list(range(lengthOf_string)) + list(range(lengthOf_string)[::-1]):\n```\nIf the current character in \'s\' is equal to \'c\', update \'lastItem_string\' with the current index \'i\'.\n```\n if s[i] == c:\n lastItem_string = i\n```\n- Calculate the minimum distance between the current index \'i\' and the last occurrence of \'c\'.\n- Update the \'result\' list with the minimum of the current distance and the previous distance.\n```\n result[i] = min(result[i], abs(i - lastItem_string))\n```\n\n\n\n | 2 | 0 | ['Array', 'Python'] | 0 |
shortest-distance-to-a-character | Best Java Solution || Beats 60% | best-java-solution-beats-60-by-ravikumar-e2vx | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ravikumar50 | NORMAL | 2023-09-12T08:57:06.452796+00:00 | 2023-09-12T08:57:06.452825+00:00 | 1,548 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] shortestToChar(String str, char c) {\n StringBuilder s = new StringBuilder(str);\n\n int ans[] = new int[s.length()];\n\n for(int i=0; i<s.length(); i++){\n if(s.charAt(i)==c){\n ans[i]=0;\n continue;\n }\n String s1 = s.substring(0,i);\n String s2 = s.substring(i+1);\n\n int a = s1.lastIndexOf(c);\n int b = s2.indexOf(c);\n\n if(a==-1) a = Integer.MAX_VALUE;\n else a = s1.length()-a;\n\n if(b==-1) b = Integer.MAX_VALUE;\n else b = b+1;\n\n\n ans[i] = Math.min(a,b);\n }\n\n return ans;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
shortest-distance-to-a-character | Easy Javascript Solution | easy-javascript-solution-by-chetannada-5ttr | 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 | chetannada | NORMAL | 2023-07-14T16:48:52.094428+00:00 | 2023-07-14T16:48:52.094451+00:00 | 115 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {string} s\n * @param {character} c\n * @return {number[]}\n */\nvar shortestToChar = function(s, c) {\n let prev = s.indexOf(c);\n let next = prev;\n const distance = [];\n for (let i = 0; i < s.length; i ++) {\n if (s[i] === c) {\n prev = i;\n next = s.indexOf(c, i + 1);\n }\n distance.push(Math.min(Math.abs(prev - i), Math.abs(next - i)));\n }\n return distance;\n};\n``` | 2 | 0 | ['JavaScript'] | 0 |
shortest-distance-to-a-character | Solution | solution-by-deleted_user-b7ts | C++ []\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n int n = s.length();\n\tvector<int>v;\n\tfor (int i = 0;i < n;i++) | deleted_user | NORMAL | 2023-05-03T12:33:15.583720+00:00 | 2023-05-03T13:35:27.617836+00:00 | 1,354 | false | ```C++ []\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n int n = s.length();\n\tvector<int>v;\n\tfor (int i = 0;i < n;i++) {\n\t\tint distance = 0;\n\t\tfor (int j = i, k = i;j < n || k >= 0;j++, k--) {\n\t\t\tif ((k >= 0 && s[k] == c) || (j < n && s[j] == c )) {\n\t\t\t\tv.push_back(distance);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdistance++;\n\t\t}\n\n\t}\n\treturn v;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n n=len(s)\n arr=[i for i in range(n) if s[i]==c]\n arr1=[]\n j=0\n for i in range(n):\n if s[i]==c:\n arr1.append(0)\n j=j+1\n elif i<arr[0]:\n arr1.append(arr[0]-i)\n elif i>arr[-1]:\n arr1.append(i-arr[-1])\n else:\n arr1.append(min(arr[j]-i,i-arr[j-1]))\n return arr1\n```\n\n```Java []\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int[] result = new int[s.length()];\n int currentIndex = -1; \n int leftIndex = findNextOccurance(s, -1, c);\n fillCreek(result, -leftIndex, leftIndex);\n while(true){\n int rightIndex = findNextOccurance( s, leftIndex, c);\n if( rightIndex == -1){\n fillCreek( result, leftIndex, s.length() + ( s.length()-1-leftIndex ));\n break;\n }\n fillCreek(result, leftIndex, rightIndex);\n leftIndex = rightIndex; \n }\n return result;\n }\n public int findNextOccurance(String s, int fromIndex, char c){\n for( int i = fromIndex+1; i< s.length(); i++){\n if( s.charAt(i) == c ) {\n return i;\n }\n }\n return -1;\n }\n public void fillCreek(int[] result, int leftIndex, int rightIndex){\n int from = Math.max( leftIndex, 0);\n int to = Math.min( rightIndex, result.length-1);\n for( int i = from ; i<= to; i++){\n result[i] = Math.min( i - leftIndex , rightIndex - i );\n }\n }\n}\n```\n | 2 | 0 | ['C++', 'Java', 'Python3'] | 1 |
shortest-distance-to-a-character | C++ Unique Solution (Beats 100%) | c-unique-solution-beats-100-by-daghansu-91mv | 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 | daghanSU | NORMAL | 2023-03-19T22:00:50.606446+00:00 | 2023-03-19T22:00:50.606488+00:00 | 519 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int>indexes;\n vector<int>sol;\n\n for(int i = 0; i < s.length(); i++)\n {\n if(s[i] == c) indexes.push_back(i);\n }\n\n for(int i = 0; i < s.length(); i++)\n {\n int min_dist = 10000;\n for(int j : indexes)\n {\n min_dist = min(min_dist,abs(j-i));\n }\n sol.push_back(min_dist);\n }\n\n return sol;\n\n\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
shortest-distance-to-a-character | Easy C++ Solution | easy-c-solution-by-clary_shadowhunters-uoj1 | \n# Code\n\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) \n {\n vector<int>ans;\n vector<int>temp;\n for | Clary_ShadowHunters | NORMAL | 2023-03-12T09:37:56.753617+00:00 | 2023-03-12T09:37:56.753650+00:00 | 1,462 | false | \n# Code\n```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) \n {\n vector<int>ans;\n vector<int>temp;\n for (int i=0;i<s.size();i++)\n {\n if (s[i]==c)\n temp.push_back(i);\n }\n int ind1=0;\n int n=temp.size();\n for (int i=0;i<s.size();i++)\n {\n if(ind1==n-1)\n {\n ans.push_back(abs(i-temp[ind1]));\n }\n else{\n if (abs(i-temp[ind1])>abs(i-temp[ind1+1]))\n {\n ind1++;\n ans.push_back(abs(i-temp[ind1]));\n }\n else{\n ans.push_back(abs(i-temp[ind1]));\n }\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
shortest-distance-to-a-character | Best Explained Solution | best-explained-solution-by-darian-catali-u69b | \n\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int len = s.length();\n int ans[] = new int[len];\n int prev = | darian-catalin-cucer | NORMAL | 2023-02-06T04:44:09.286577+00:00 | 2023-02-06T04:44:09.286623+00:00 | 817 | false | \n```\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int len = s.length();\n int ans[] = new int[len];\n int prev = len;\n \n // forward\n for(int i = 0; i < len; i++){\n if(s.charAt(i) == c){\n prev = 0;\n ans[i] = 0;\n }\n else\n ans[i] = ++prev;\n }\n \n prev = len;\n for(int i = len-1; i >= 0; i--){\n if(s.charAt(i) == c){\n prev = 0;\n ans[i] = Math.min(ans[i], 0);\n }\n else\n ans[i] = Math.min(ans[i], ++prev);\n }\n \n return ans;\n }\n}\n\n``` | 2 | 1 | ['Go', 'Scala', 'Ruby', 'Kotlin', 'Bash'] | 0 |
shortest-distance-to-a-character | C++ solution for beginners | c-solution-for-beginners-by-shristha-yyhy | \n\n# Code\n\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int>ispresent;\n for(int i=0;i<s.length();i++ | Shristha | NORMAL | 2023-01-23T17:13:50.714266+00:00 | 2023-01-23T17:13:50.714337+00:00 | 1,453 | false | \n\n# Code\n```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int>ispresent;\n for(int i=0;i<s.length();i++){\n if(s[i]==c)ispresent.push_back(i);\n }\n vector<int>ans(s.length());\n for(int i=0;i<s.length();i++){\n if(s[i]==c){\n ans[i]=0;\n }\n else{\n int val=INT_MAX;\n for(int k=0;k<ispresent.size();k++){\n val=min(val,abs(i-ispresent[k]));\n }\n ans[i]=val;\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
shortest-distance-to-a-character | Shortest distance to a Character | shortest-distance-to-a-character-by-bibe-yi5p | Intuition\n Describe your first thoughts on how to solve this problem. two traversals from each end..and then assigning the minimum of them both!\n\n# Approach\ | bibek_codes | NORMAL | 2022-12-06T07:20:58.384197+00:00 | 2022-12-06T07:20:58.384231+00:00 | 59 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->two traversals from each end..and then assigning the minimum of them both!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->Two loops taken from left and right traversal assigning distance acc. to the closest occurence of the character \'c\'\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n \n int len=(int)s.size();\n vector<int> ans(len,INT_MAX);\n \n int pos=-1;\n \n for(int i=0;i<len;i++)\n {\n if(s[i]==c)\n {\n pos=i;\n }\n \n if(pos!=-1)\n {\n ans[i]=(i-pos);\n }\n }\n pos=-1;\n \n for(int i=len-1;i>=0;i--)\n {\n if(s[i]==c)\n {\n pos=i;\n }\n \n if(pos!=-1)\n {\n ans[i]=min(ans[i],(pos-i));\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Two Pointers', 'String', 'C++'] | 0 |
shortest-distance-to-a-character | Runs 100% Faster Cpp soln | O(N) | runs-100-faster-cpp-soln-on-by-mk28r-xn7t | ```cpp\nclass Solution {\npublic:\n vector shortestToChar(string s, char c) {\n int n = s.size();\n vector ans(s.size());\n int last = - | TIME2LIVE | NORMAL | 2022-10-26T19:35:46.709053+00:00 | 2022-10-26T19:35:46.709090+00:00 | 23 | false | ```cpp\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n int n = s.size();\n vector<int> ans(s.size());\n int last = -n ;\n for(int i = 0 ; i < n ;i++){\n if(s[i]==c)\n last= i ; \n \n ans[i]=(i-last);\n }\n for(int i = n-1 ; i >= 0 ;i--){\n if(s[i]==c)\n last= i ; \n \n ans[i]=(min(abs(last-i) , ans[i]));\n }\n return ans;\n \n }\n}; | 2 | 0 | ['C++'] | 0 |
shortest-distance-to-a-character | [Python] Simplest Solution | python-simplest-solution-by-darpangoel07-n5lf | \n\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n temp = []\n ind = s.index(c)\n for i in range(len(s)):\n | darpangoel07 | NORMAL | 2022-09-18T10:12:12.842093+00:00 | 2022-09-18T10:13:20.934598+00:00 | 987 | false | ```\n\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n temp = []\n ind = s.index(c)\n for i in range(len(s)):\n if abs(ind-i)>abs(s.find(c,i)-i):\n ind = s.index(c,i)\n if s[i]!=c:\n temp.append(abs(ind-i))\n else:\n temp.append(0)\n return temp\n``` | 2 | 0 | ['Python'] | 0 |
shortest-distance-to-a-character | [C++] Fast and Easy iterative solution | c-fast-and-easy-iterative-solution-by-cy-ipaz | \nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n int fdist=INT_MAX,bdist=INT_MAX;\n vector<int>ans(s.size(),INT_M | cyberReckon | NORMAL | 2022-09-12T09:59:00.286802+00:00 | 2022-09-12T09:59:00.286834+00:00 | 389 | false | ```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n int fdist=INT_MAX,bdist=INT_MAX;\n vector<int>ans(s.size(),INT_MAX);\n for(int i=0,j=s.size()-1;i<s.size();++i,--j)\n {\n if(s[i]==c) fdist=0;\n if(s[j]==c) bdist=0;\n \n ans[i]=min(fdist,ans[i]);\n ans[j]=min(bdist,ans[j]);\n \n if(fdist!=INT_MAX) fdist++;\n if(bdist!=INT_MAX) bdist++;\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C', 'Iterator'] | 0 |
shortest-distance-to-a-character | JS easy solution 100% | js-easy-solution-100-by-kunkka1996-s1hi | \nvar shortestToChar = function(s, c) {\n const indexOfC = [];\n const output = [];\n \n for (let i = 0; i < s.length; i++) {\n if (s[i] === | kunkka1996 | NORMAL | 2022-09-09T08:12:28.965274+00:00 | 2022-09-09T08:12:28.965313+00:00 | 909 | false | ```\nvar shortestToChar = function(s, c) {\n const indexOfC = [];\n const output = [];\n \n for (let i = 0; i < s.length; i++) {\n if (s[i] === c) {\n indexOfC.push(i)\n }\n }\n \n for (let i = 0; i < s.length; i++) {\n output[i] = +Infinity;\n for (let j = 0; j < indexOfC.length; j++) {\n if (i === indexOfC[j]) {\n output[i] = 0;\n break;\n } else {\n if (Math.abs(indexOfC[j] - i) > output[i]) break;\n output[i] = Math.min(output[i], Math.abs(indexOfC[j] - i));\n }\n }\n }\n \n return output;\n};\n``` | 2 | 0 | ['JavaScript'] | 0 |
shortest-distance-to-a-character | O(1) Space Prefix / Suffix With Comments 🔥 | o1-space-prefix-suffix-with-comments-by-mpr7v | \n# Python\n def shortestToChar(self, s: str, c: str) -> List[int]:\n\t """\n Q. Min/Max distance to closest character [left or right]\n \n | xxvvpp | NORMAL | 2022-09-05T07:41:52.700716+00:00 | 2022-09-05T07:42:16.042674+00:00 | 337 | false | \n# Python\n def shortestToChar(self, s: str, c: str) -> List[int]:\n\t """\n Q. Min/Max distance to closest character [left or right]\n \n Character can be present to left or right both\n \n 1. Trace from left to right & count distance from last char found\n 2. Trace from right to left:\n Three cases would be there: \n \n Case1: [a _ _ _ _ _ a] -> already non-zero & flag true from right, take min\n Case2: [a _ _ _ _ _ _] -> already non-zero & flag false, then leave\n Case3: [_ _ _ _ _ _ a] -> already zero & flag true, update the sum \n """\n n= len(s)\n pre= [0 for i in range(0,n)]\n flag= False\n \n for i in range(0,n):\n if s[i]==c: flag=True\n elif flag: pre[i]= pre[i-1]+1\n \n flag=False;\n \n for i in range(n-1,-1,-1):\n if s[i]==c: flag=True \n elif flag and pre[i]==0: pre[i]= pre[i+1]+1\n elif flag and pre[i]>0: pre[i]= min(pre[i],pre[i+1]+1) \n return pre | 2 | 0 | ['Python'] | 0 |
shortest-distance-to-a-character | Easiest Approach 5 ms || with Explanation | easiest-approach-5-ms-with-explanation-b-8bxb | \nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int>sk;\n vector<int>res;\n vector<int>temp;\n | sagarkesharwnnni | NORMAL | 2022-08-07T18:27:29.175120+00:00 | 2022-08-07T18:28:09.504025+00:00 | 400 | false | ```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int>sk;\n vector<int>res;\n vector<int>temp;\n int ss=0;\n int mins;\n for(int i=0;i<s.length();i++){\n if(s[i]==c)\n\t\t\t//storing all the c character location i.e \'e\' in sk i.e [3,5,6,11]\n sk.push_back(i);\n }\n for(int i=0;i<s.length();i++){\n for(int j=0;j<sk.size();j++){\n\t\t\t//now subtracting every i value with all value of character locations and storing the minimum in res vector.\n\t\t\n mins=abs(sk[j]-i);\n temp.push_back(mins);\n }\n\t\t\t\t//in first iteration [3-0=3,5-0=5,6-0=6,11-0=0] so removing the minimum elemnet from this that is 3 and stroing is res.\n int min=temp[0];\n for(auto i:temp){\n if(i<min){\n min=i;\n }\n }\n res.push_back(min);\n temp.clear();\n \n }\n\n return res;\n }\n};\n``` | 2 | 0 | ['C'] | 0 |
shortest-distance-to-a-character | C++ O(n) solution easy to understand | c-on-solution-easy-to-understand-by-ayum-iwpm | \nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c)\n {\n int a=s.length();\n int arr1[a];\n int arr2[a];\n | ayumsh | NORMAL | 2022-07-14T13:13:23.347182+00:00 | 2022-07-14T13:13:23.347234+00:00 | 60 | false | ```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c)\n {\n int a=s.length();\n int arr1[a];\n int arr2[a];\n for(int i=0;i<s.length();i++)\n {\n arr1[i]=100000;\n arr2[i]=100000;\n }\n int occur1;\n int flag1=0;\n for(int i=0;i<s.length();i++)\n {\n if(s[i]==c)\n {\n arr1[i]=0;\n flag1=1;\n occur1=i;\n }\n if (flag1==1)\n {\n arr1[i]=i-occur1;\n }\n }\n int occur2;\n int flag2=0;\n for(int i=a-1;i>=0;i--)\n {\n if(s[i]==c)\n {\n arr2[i]=0;\n flag2=1;\n occur2=i;\n }\n if (flag2==1)\n {\n arr2[i]=occur2-i;\n }\n }\n vector<int> ans;\n for(int i=0;i<s.length();i++)\n {\n int mele=min(arr1[i],arr2[i]);\n ans.push_back(mele);\n }\n \n return ans;\n \n }\n};\n``` | 2 | 0 | ['C'] | 0 |
shortest-distance-to-a-character | Python3 O(n) || O(n) # Runtime: 53ms 78.92% Memory: 13.9mb 91.60% | python3-on-on-runtime-53ms-7892-memory-1-1orf | \nclass Solution:\n def shortestToChar(self, string: str, char: str) -> List[int]:\n return self.optimalSolution(string, char)\n# O(n) || O(n)\n# | arshergon | NORMAL | 2022-06-22T16:16:20.076274+00:00 | 2022-06-22T16:16:20.076312+00:00 | 1,159 | false | ```\nclass Solution:\n def shortestToChar(self, string: str, char: str) -> List[int]:\n return self.optimalSolution(string, char)\n# O(n) || O(n)\n# Runtime: 53ms 78.92% Memory: 13.9mb 91.60%\n def optimalSolution(self, string, char):\n n = len(string)\n leftArray, rightArray, result = ([float(\'inf\')] * n, \n [float(\'inf\')] * n, \n [float(\'inf\')] * n)\n temp = float(\'inf\')\n for i in range(len(string)):\n if string[i] == char:\n temp = 0\n leftArray[i] = temp\n temp += 1\n\n temp = float(\'inf\')\n for i in reversed(range(len(string))):\n if string[i] == char:\n temp = 0\n rightArray[i] = temp\n temp += 1\n\n\n for i in range(len(result)):\n result[i] = min(leftArray[i], rightArray[i])\n\n return result\n\n \n# O(n^2) || O(n) Runtime: TLE\n def bruteForce(self, string, char):\n sequence = [float(\'inf\')] * len(string)\n newList = []\n for idx, val in enumerate(string):\n if val == char:\n newList.append(idx)\n\n for val1 in newList:\n for idx2, val2 in enumerate(string):\n sequence[idx2] = min(sequence[idx2], abs(idx2-val1))\n\n return sequence\n``` | 2 | 0 | ['Two Pointers', 'Python', 'Python3'] | 0 |
shortest-distance-to-a-character | Nice Solution in C++ | nice-solution-in-c-by-dev-madhurendra-grbl | \nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int> ans;\n int n = s.size();\n for(int i=0;i<n;++ | dev-madhurendra | NORMAL | 2022-05-31T15:05:54.885080+00:00 | 2022-05-31T15:05:54.885126+00:00 | 93 | false | ```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int> ans;\n int n = s.size();\n for(int i=0;i<n;++i){\n if(s[i]==c){\n ans.push_back(0);\n }\n else{\n int st = i;\n int en = i;\n bool find1=false,find2=false;\n while(st>=0){\n if(s[st]==c){\n find1 = true;\n break;\n }\n st--;\n }\n while(en<n){\n if(s[en]==c){\n find2 = true;\n break;\n }\n en++;\n }\n if(find1 && find2){\n ans.push_back(min(en-i,i-st)); \n }else if(find1){\n ans.push_back(i-st);\n }else{\n ans.push_back(en-i);\n }\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | [] | 0 |
shortest-distance-to-a-character | java || too easy solution | java-too-easy-solution-by-pratham_18-lpnj | //do upvote :)\n\n\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int ans[]=new int[s.length()];\n ArrayList<Integer> li | Pratham_18 | NORMAL | 2022-05-10T11:51:50.451195+00:00 | 2022-05-10T11:51:50.451219+00:00 | 153 | false | //do upvote :)\n\n```\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int ans[]=new int[s.length()];\n ArrayList<Integer> li=new ArrayList<>();\n //Store the index of the character\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)==c){\n li.add(i);\n }\n }\n for(int i=0;i<s.length();i++){\n int min=Integer.MAX_VALUE;\n for(int j=0;j<li.size();j++){\n int x=Math.abs(i-li.get(j));\n if(x<min){\n min=x;\n }\n }\n ans[i]=min;\n }\n return ans;\n }\n}``` | 2 | 0 | ['Java'] | 0 |
shortest-distance-to-a-character | Shortest Distance to a Character | shortest-distance-to-a-character-by-sbar-h6om | \nvector<int> shortestToChar(string s, char c) {\n vector<int> index;\n vector<int> ans;\n int k1 = 0, k2 = 1;\n for(int i = 0; i < | sbaraniya01 | NORMAL | 2022-04-26T15:39:33.940854+00:00 | 2022-04-26T15:39:33.940881+00:00 | 209 | false | ```\nvector<int> shortestToChar(string s, char c) {\n vector<int> index;\n vector<int> ans;\n int k1 = 0, k2 = 1;\n for(int i = 0; i < s.length(); i++)\n {\n if(s[i] == c)\n {\n index.push_back(i);\n }\n }\n index.push_back(INT_MAX);\n for(int i = 0; i < s.length(); i++)\n {\n if(i > index[k2])\n {\n k1++;\n k2++;\n }\n ans.push_back(min(abs(index[k1]-i),abs(index[k2]-i)));\n }\n return ans;\n }\n``` | 2 | 0 | ['C'] | 0 |
shortest-distance-to-a-character | Easy To Understand Java Code | easy-to-understand-java-code-by-riteshbh-mpx4 | \nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int min=Integer.MAX_VALUE;\n int[] array=new int[s.length()];\n f | riteshbhardwaj0001 | NORMAL | 2022-02-02T09:30:51.242691+00:00 | 2022-02-02T09:30:51.242721+00:00 | 89 | false | ```\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int min=Integer.MAX_VALUE;\n int[] array=new int[s.length()];\n for(int i=0;i<s.length();i++){\n for(int j=0;j<s.length();j++){\n if(s.charAt(j)==c){\n min=Math.min(min,Math.abs(i-j));\n } \n }\n array[i]=min;\n min=Integer.MAX_VALUE;\n }\n return array;\n }\n}\n``` | 2 | 0 | [] | 1 |
shortest-distance-to-a-character | (Beats 100% Runtime) Optimal 2-Pass in Python | beats-100-runtime-optimal-2-pass-in-pyth-ec1j | \nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n #Time: O(n)\n #Space: O(n)\n \n #Represents how far | surin_lovejoy | NORMAL | 2022-01-25T09:43:36.336980+00:00 | 2022-01-25T09:46:37.152252+00:00 | 190 | false | ```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n #Time: O(n)\n #Space: O(n)\n \n #Represents how far a character is away from c (x = inf)\n #loveleetcode\n #xxx010012340 - first pass\n #321010043210 - second pass\n #321010012210 - answer (take min of both first and second pass)\n \n answer = [float(\'inf\') for _ in range(len(s))]\n \n counter = float(\'inf\')\n for idx in range(len(s)):\n #Run into a C -> reset our counter\n if s[idx] == c:\n counter = 0\n #Run into something else -> increment our counter and assign the count to answer\n else:\n counter += 1\n \n answer[idx] = min(answer[idx], counter)\n \n counter = float(\'inf\')\n for idx in reversed(range(len(s))):\n #Run into a C -> reset our counter\n if s[idx] == c:\n counter = 0\n #Run into something else -> increment our counter and assign the count to answer\n else:\n counter += 1\n \n answer[idx] = min(answer[idx], counter)\n \n return answer\n``` | 2 | 0 | ['Python'] | 0 |
shortest-distance-to-a-character | Easy solution Using C++ | easy-solution-using-c-by-cryp2coder420-amvu | vector shortestToChar(string s, char c) {\n vector v;\n for (int i = 0; i < s.size(); i++)\n {\n if (s[i] == c)\n | cryp2coder420 | NORMAL | 2021-10-06T03:14:38.167443+00:00 | 2021-10-06T03:14:38.167494+00:00 | 91 | false | # vector<int> shortestToChar(string s, char c) {\n vector<int> v;\n for (int i = 0; i < s.size(); i++)\n {\n if (s[i] == c)\n v.push_back(i);\n }\n\n vector<int> result;\n int index, diff;\n for (int i = 0; i < s.size(); i++)\n {\n index = INT_MAX;\n for (int j = 0; j < v.size(); j++)\n {\n diff = abs(i - v[j]);\n index = min(index, diff);\n }\n result.push_back(index);\n }\n\n return result;\n } | 2 | 0 | [] | 0 |
shortest-distance-to-a-character | Easy to understand, O(N), [C++, Java] | easy-to-understand-on-c-java-by-akashsah-cg55 | Implementation\n\n1st Approach in C++\nTime Complexity = O(N), Space Complexity = O(N)\n\n\nvector<int> shortestToChar(string s, char c) {\n vector<int> vec, | akashsahuji | NORMAL | 2021-06-10T05:25:54.479871+00:00 | 2021-06-10T05:25:54.479919+00:00 | 387 | false | Implementation\n\n**1st Approach in C++**\nTime Complexity = O(N), Space Complexity = O(N)\n\n```\nvector<int> shortestToChar(string s, char c) {\n vector<int> vec, res;\n for(int itr = 0; itr < s.size(); itr++){\n if(s[itr] == c) vec.push_back(itr);\n }\n \n int dif1 = 0, dif2 = 0; \n for(int jtr = 0, itr = 0; itr < s.size(); itr++){\n if(vec[jtr] >= itr || jtr+1 == vec.size()) res.push_back(abs(vec[jtr]-itr));\n else{\n dif1 = abs(vec[jtr+1]-itr);\n dif2 = abs(vec[jtr]-itr);\n if(dif1 <= dif2){\n res.push_back(dif1);\n jtr++;\n }\n else res.push_back(dif2);\n }\n }\n return res; \n}\n```\n\n\n**2nd Approach in Java**\nTime Complexity = O(N), Space Complexity = O(N)\n\n```\npublic int[] shortestToChar(String s, char c) {\n ArrayList<Integer> arr = new ArrayList<Integer>(); \n for(int itr = 0; itr < s.length(); itr++){\n if(s.charAt(itr) == c) arr.add(itr);\n }\n\t\n int[] res = new int[s.length()];\n int dif1 = 0, dif2 = 0; \n for(int jtr = 0, itr = 0; itr < s.length(); itr++){\n if(arr.get(jtr) >= itr || jtr+1 == arr.size()) res[itr] = Math.abs(arr.get(jtr)-itr);\n else{ \n dif1 = Math.abs(arr.get(jtr+1)-itr);\n dif2 = Math.abs(arr.get(jtr)-itr);\n if(dif1 <= dif2){\n res[itr] = dif1;\n jtr++;\n }\n else res[itr] = dif2;\n }\n }\n return res; \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 :)\n | 2 | 0 | ['Array', 'String', 'C', 'Java'] | 0 |
shortest-distance-to-a-character | C++ Simplest Solution | c-simplest-solution-by-nandini_77-gknc | \nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n int n = s.size();\n vector<int> ans(n,0);\n int prev = -1 | nandini_77 | NORMAL | 2021-02-13T09:48:25.776946+00:00 | 2021-02-13T09:48:25.776978+00:00 | 193 | false | ```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n int n = s.size();\n vector<int> ans(n,0);\n int prev = -1;\n for(int i = 0; i<n; i++){\n if(s[i] == c)\n prev = i;\n if(prev!=-1)\n ans[i] = i - prev; \n else\n ans[i] = INT_MAX;\n }\n prev = -1;\n for(int i = n-1; i>=0; i--){\n if(s[i] == c)\n prev = i;\n if(prev!=-1)\n ans[i] = min(ans[i],prev - i);\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C'] | 0 |
shortest-distance-to-a-character | [Python/Python3] Shortest Distance to a Character | pythonpython3-shortest-distance-to-a-cha-p8uc | ShamelessSelfPromotion: My other leetcode solutions to various questions can be found here\n\nThis algorithm is called 2-Pass as we iterate through array twice: | newborncoder | NORMAL | 2021-02-09T03:28:24.378117+00:00 | 2021-05-10T09:15:24.688803+00:00 | 306 | false | ***ShamelessSelfPromotion***: My other leetcode [solutions](https://leetcode.com/discuss/general-discussion/1112952/Collection-of-my-leetcode-solution-posts) to various questions can be found [here](https://leetcode.com/discuss/general-discussion/1112952/Collection-of-my-leetcode-solution-posts)\n\nThis algorithm is called 2-Pass as we iterate through array twice:\n1. Left to Right\n2. Right to Left\nThis will give us the optimal solution\n\nTime: ```O(N)```\nSpace:```O(N)```\n\nSolution:\n```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n \n final = [float(\'inf\') for x in range(len(s))]\n final_final = []\n \n\t\t# assigning 10**4 + 1 value as the length of string is less than that and hence\n\t\t# our answer will be less than that. We can assign float(\'inf\') here also.\n nearest_c = 10001\n \n\t\t# Here, we are going from left to right and calculating the distance from out target\n\t\t# character c to other characters\n\t\tfor idx, val in enumerate(s):\n if val == c:\n nearest_c = 0\n final[idx] = 0\n elif nearest_c != float(\'inf\'):\n nearest_c += 1\n final[idx] = min(final[idx], nearest_c)\n \n \n # assigning 10**4 + 1 value as the length of string is less than that and hence\n\t\t# our answer will be less than that. We can assign float(\'inf\') here also.\n nearest_c = 10001\n \n\t\t# Here we are going from right to left so that we can make sure that the distance between\n\t\t# the target character is lowest from front and back.\n for idx in range(len(s))[::-1]:\n if s[idx] == c:\n nearest_c = 0\n elif nearest_c != float(\'inf\'):\n nearest_c += 1\n # final[idx] = nearest_c\n final[idx] = min(final[idx], nearest_c)\n \n # print(final)\n \n return final\n```\n | 2 | 1 | ['Python', 'Python3'] | 0 |
prime-number-of-set-bits-in-binary-representation | 665772 | 665772-by-stefanpochmann-sli1 | Ruby:\n\ndef count_prime_set_bits(l, r)\n (l..r).sum { |i| 665772 >> i.digits(2).sum & 1 }\nend\n\nPython:\n\n def countPrimeSetBits(self, L, R):\n r | stefanpochmann | NORMAL | 2018-01-14T07:03:16.079000+00:00 | 2018-09-06T03:28:50.057218+00:00 | 9,426 | false | Ruby:\n```\ndef count_prime_set_bits(l, r)\n (l..r).sum { |i| 665772 >> i.digits(2).sum & 1 }\nend\n```\nPython:\n\n def countPrimeSetBits(self, L, R):\n return sum(665772 >> bin(i).count('1') & 1 for i in range(L, R+1))\n\nJava stream:\n\n public int countPrimeSetBits(int L, int R) {\n return IntStream.range(L, R+1).map(i -> 665772 >> Integer.bitCount(i) & 1).sum();\n }\n\nJava:\n\n public int countPrimeSetBits(int L, int R) {\n int count = 0;\n while (L <= R)\n count += 665772 >> Integer.bitCount(L++) & 1;\n return count;\n }\n\nC++:\n\n int countPrimeSetBits(int L, int R) {\n int count = 0;\n while (L <= R)\n count += 665772 >> __builtin_popcount(L++) & 1;\n return count;\n } | 211 | 10 | [] | 24 |
prime-number-of-set-bits-in-binary-representation | [Java/C++] Clean Code | javac-clean-code-by-alexander-b156 | Java\n\nclass Solution {\n public int countPrimeSetBits(int l, int r) {\n Set<Integer> primes = new HashSet<>(Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19 | alexander | NORMAL | 2018-01-14T04:02:46.739000+00:00 | 2018-10-24T14:51:54.154335+00:00 | 13,805 | false | **Java**\n```\nclass Solution {\n public int countPrimeSetBits(int l, int r) {\n Set<Integer> primes = new HashSet<>(Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19 /*, 23, 29 */ ));\n int cnt = 0;\n for (int i = l; i <= r; i++) {\n int bits = 0;\n for (int n = i; n > 0; n >>= 1)\n bits += n & 1;\n cnt += primes.contains(bits) ? 1 : 0;\n }\n return cnt; \n }\n}\n```\n**C++**\n```\nclass Solution {\npublic:\n int countPrimeSetBits(int l, int r) {\n set<int> primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };\n int cnt = 0;\n for (int i = l; i <= r; i++) {\n int bits = 0;\n for (int n = i; n; n >>= 1)\n bits += n & 1;\n cnt += primes.count(bits);\n }\n return cnt;\n }\n};\n``` | 70 | 2 | [] | 14 |
prime-number-of-set-bits-in-binary-representation | Sort Easy Python | sort-easy-python-by-localhostghost-02yb | \nclass Solution:\n def countPrimeSetBits(self, L, R):\n """\n :type L: int\n :type R: int\n :rtype: int\n """\n pr | localhostghost | NORMAL | 2018-02-12T04:56:46.093000+00:00 | 2018-10-25T14:23:48.715185+00:00 | 3,632 | false | ```\nclass Solution:\n def countPrimeSetBits(self, L, R):\n """\n :type L: int\n :type R: int\n :rtype: int\n """\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n return sum(map(lambda x: bin(x).count('1') in primes, range(L, R+1)))\n``` | 38 | 0 | [] | 4 |
prime-number-of-set-bits-in-binary-representation | Easy O(n) Java solution using DP | easy-on-java-solution-using-dp-by-ashish-dsj5 | \nclass Solution {\n public int countPrimeSetBits(int L, int R) {\n int cnt = 0;\n Set<Integer> listPrimes = new HashSet<>(Arrays.asList(2, 3, | ashish53v | NORMAL | 2018-01-14T04:09:44.167000+00:00 | 2018-08-11T16:08:26.213838+00:00 | 4,480 | false | ```\nclass Solution {\n public int countPrimeSetBits(int L, int R) {\n int cnt = 0;\n Set<Integer> listPrimes = new HashSet<>(Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ));\n int[] res = countBits(R);\n for(int i=L;i<=R;i++){\n if(listPrimes.contains(res[i])){\n cnt++;\n } \n }\n return cnt;\n } \n \n public int[] countBits(int num) {\n if(num == 0)\n return new int[1];\n int[] dp = new int[num+1];\n \n dp[0] = 0;\n dp[1] = 1;\n \n for(int i=2;i<=num;i++){\n dp[i] = dp[i >> 1] + dp[i & 1]; // i >> 1 is i / 2 and i & 1 is i % 2\n }\n return dp;\n }\n}\n``` | 25 | 2 | [] | 4 |
prime-number-of-set-bits-in-binary-representation | A fast algorithm utilizing Pascal's Triangle | a-fast-algorithm-utilizing-pascals-trian-a0on | Simple scenarios\nLet\'s observe first, how we may count the total number of set bits from (L,0]. We start with "simple numbers", e.g. 0b10000, with a 1 at posi | zhoulytwin | NORMAL | 2018-08-09T04:45:21.740163+00:00 | 2018-08-31T22:41:40.417266+00:00 | 1,430 | false | ## Simple scenarios\nLet\'s observe first, how we may count the total number of set bits from `(L,0]`. We start with "simple numbers", e.g. `0b10000`, with a `1` at position `n` followed by `n-1` `0`s:\n\n|n| L | Possible bit combos within (L,0] | 0 set bits | 1 set bits | 2 set bits | 3 set bits |\n|-|----------|-------------------------------------------|-------------|-------------|-------------|-------------|\n|1| `0b1` | `0b0` | 1 | | | |\n|2| `0b10` | `0b1`, `0b0` | 1 | 1 | | |\n|3|`0b100`| `0b11`, `0b10`, `0b1`, `0b0` | 1 | 2 | 1 | |\n|4|`0b1000`| `0b111`, `0b110`, `0b101`, `0b100`, `0b11`, `0b10`, `0b1`, `0b0` | 1 | 3 | 3 | 1 |\n\n\\* It can be proven easily using combinatorics, that the number of set bits of such a "simple number" follows the Pascal\'s Triangle.\n\n## More complex scenarios\nGiven a more complex number, such as `0b1100`, the number of set bits within `(0b1100,0]` can be obtained by combining the set bits in two ranges: 1) `(0b1100,0b1000]` and 2) `(0b1000,0]`. The set bits of range 2 can be directly looked up in our Pascal Triangle. The set bit of range 1 is a bit tricky. You look up `0b100` in the triangle, which gives you `{0:1,1:2, 2:1}` and then you shift the set bit by 1 to obtain `{1:1, 2:2, 3:1}`. This is to accomodate the fact that there is a bit `1` ahead of `0b100`.\nGiven more comples numbers and you may need to divide it into several ranges and use a similar procesure to get the number of set bits.\n\nSo that is the idea of using Pascal Triangle to obtain set bits in range `(L,0]`. With a little modification, one can get the prime number of set bits in range `[L,R]`.\n\n## Time complexity\nThe time complexity is in the order of `O(N^2)` where `N` is the position of the most significant bit in `R`.\n\n## Sample Code\nPython for expresiveness.\n\n```\nclass Solution:\n def getMostSignificantBitPosition(self,num):\n """\n param: A *positive* number\n return: The position of the most significant bit\n\n Example:\n Given 0b101001\n Return 6\n """\n return len(bin(num))-len("0b")\n\n def getPascalTriangle(self, num):\n """\n param: The desired triangle level\n return: A pascal triangle of desired leven\n\n Example\n Given 4\n Return [[1] index:0 level:1\n [1,1]\n [1,2,1]\n [1,3,3,1]\n ]\n #bit set 0 1 2 3 ...\n """\n # Assume num>=1\n ret = [[1]]\n for i in range(1,num):\n tmp=[1]\n for m,n in zip(ret[i-1][1:],ret[i-1][:-1]):\n tmp.append(m+n)\n tmp.append(1)\n\n ret.append(tmp)\n return ret\n\n def getPrimeBitSets(self,num,PascalTriangle):\n """\n param: a positive number smaller than 2^32\n param: a pascal triangle of enough level\n return: the number of prime bit sets in range (num,0]\n\n Example\n Given 0b1001\n Return\n """\n # Prime table\n # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\n # 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32\n isPrime = [0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0,\n 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0]\n primeCount = 0\n prevBitCount = 0\n pos = self.getMostSignificantBitPosition(num)\n for p in range(pos,0,-1): # p for position\n mask = 1 << (p-1)\n if mask & num == 0:\n continue\n\n # Encountered bit \'1\'\n # Loop up the triangle for prime bit sets\n for n,v in enumerate(PascalTriangle[p-1]): # n for bit sets\n if isPrime[n+prevBitCount]:\n primeCount+=v\n # END FOR\n\n prevBitCount+=1\n # END FOR\n return primeCount\n\n def countPrimeSetBits(self, L, R):\n """\n :type L: int\n :type R: int\n :rtype: int\n """\n\n # To obtain prime number of bit sets in range [R,L]\n # We opt to obtain prime number of bit sets\n # in range (R+1,0] and (L,0] and use subtraction to\n # obtain that in range [R,L]\n\n # Needed to run getPrimeBitSets(R+1,trangle)\n triangle = self.getPascalTriangle(\n self.getMostSignificantBitPosition(R+1) )\n return self.getPrimeBitSets(R+1,triangle)-self.getPrimeBitSets(L,triangle)\n``` | 16 | 0 | [] | 3 |
prime-number-of-set-bits-in-binary-representation | Python 1 line | python-1-line-by-guofei9987-hxy7 | \nclass Solution:\n def countPrimeSetBits(self, L, R):\n """\n :type L: int\n :type R: int\n :rtype: int\n """\n re | guofei9987 | NORMAL | 2018-08-15T07:54:11.924189+00:00 | 2018-09-03T16:35:02.240974+00:00 | 1,632 | false | ```\nclass Solution:\n def countPrimeSetBits(self, L, R):\n """\n :type L: int\n :type R: int\n :rtype: int\n """\n return len([1 for i in range(L,R+1) if bin(i).count(\'1\') in [2, 3, 5, 7, 11, 13, 17, 19]])\n``` | 14 | 0 | [] | 3 |
prime-number-of-set-bits-in-binary-representation | c++ implementation for every function | c-implementation-for-every-function-by-m-8ygo | \nclass Solution {\npublic:\n \n int count_of_bits(int num){ //function to return number of bits\n int count = 0;\n while (num > 0){\n | minhphanhvu | NORMAL | 2020-07-23T20:25:24.123359+00:00 | 2020-07-23T20:25:24.123392+00:00 | 1,546 | false | ```\nclass Solution {\npublic:\n \n int count_of_bits(int num){ //function to return number of bits\n int count = 0;\n while (num > 0){\n if (num % 2 == 1){\n count +=1;\n num = num/2;\n }\n else{\n num = num/2;\n }\n }\n return count;\n }\n //-----\n bool if_prime(int num){ //function to return if a number is prime(true) or not(false)\n if (num <=1){ //0 and 0 is not prime\n return false;\n }\n int i =2;\n while (i <= (num/2)){\n if (num % i == 0){\n return false;\n }\n i++;\n }\n return true;\n }\n //-----\n int countPrimeSetBits(int L, int R) {\n int res = 0;\n int count;\n for (int i = L; i <= R; i++){\n count = count_of_bits(i);\n if (if_prime(count)){\n res +=1;\n }\n }\n return res;\n }\n};\n``` | 10 | 1 | ['C', 'C++'] | 1 |
prime-number-of-set-bits-in-binary-representation | Fast Python beats 100% (40ms, uses binomial coefficients) | fast-python-beats-100-40ms-uses-binomial-ttsl | Using this formula\n\nwe can obtain some fast code. There are O(log^2 N / log log N) binomial coefficients in this sum, I think. Note that the binomial coeffici | gd303 | NORMAL | 2018-08-08T12:38:45.886161+00:00 | 2018-08-08T12:38:45.886161+00:00 | 1,600 | false | Using this formula\n\nwe can obtain some fast code. There are O(log^2 N / log log N) binomial coefficients in this sum, I think. Note that the binomial coefficient cache is global across test cases.\n```\ndef binomial(n, k, cache={}):\n if k == 0: return 1\n if (n, k) not in cache:\n cache[n, k] = binomial(n-1, k-1) * n // k\n return cache[n, k]\n\n\nclass Solution:\n def countPrimeSetBits(self, L, R):\n return self.fast_count(R+1) - self.fast_count(L)\n \n def fast_count(self, N):\n S = bin(N)\n B = [len(S) + ~i for i, b in enumerate(S) if b == \'1\']\n res = 0\n for p in [2, 3, 5, 7, 11, 13, 17, 19]:\n if B[0] < p: break\n for i in range(min(p+1, len(B))):\n n = B[i]; k = p-i\n if n < k: break\n res += binomial(n, k)\n return res\n``` | 10 | 0 | [] | 5 |
prime-number-of-set-bits-in-binary-representation | Easy Python solution | easy-python-solution-by-vistrit-jgut | \ndef countPrimeSetBits(self, left: int, right: int) -> int:\n count=0\n for i in range(left,right+1):\n c=0\n n=bin(i).coun | vistrit | NORMAL | 2021-12-05T06:02:12.398473+00:00 | 2021-12-05T06:02:12.398505+00:00 | 987 | false | ```\ndef countPrimeSetBits(self, left: int, right: int) -> int:\n count=0\n for i in range(left,right+1):\n c=0\n n=bin(i).count("1")\n for j in range(1,n+1):\n if n%j==0:\n c+=1\n if c==2:\n count+=1\n return count\n``` | 7 | 0 | ['Python', 'Python3'] | 1 |
prime-number-of-set-bits-in-binary-representation | Application of Wilson's theorem | application-of-wilsons-theorem-by-treema-wohi | It follows Wilson\'s theorem to perform one-liner test for prime. But to create the hash table is still quicker.\npython\nclass Solution(object):\n def count | treemantan | NORMAL | 2019-12-02T09:37:11.312320+00:00 | 2019-12-02T09:37:11.312368+00:00 | 651 | false | It follows [Wilson\'s theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem) to perform one-liner test for prime. But to create the hash table is still quicker.\n```python\nclass Solution(object):\n def countPrimeSetBits(self, L, R):\n """\n :type L: int\n :type R: int\n :rtype: int\n """\n res = 0\n for i in range(L,R+1):\n bits= bin(i).count(\'1\')\n if bits!=1 and math.factorial(bits - 1) % bits == bits - 1:\n res+=1\n return res\n``` | 7 | 0 | ['Python'] | 2 |
prime-number-of-set-bits-in-binary-representation | Python simple solution w/ explanation | python-simple-solution-w-explanation-by-y0pbp | The most intuitive way to count for 1\'s in the binary expression of a number, is counting the 1\'s. Luckily, python can do that using .count() method. \n\nSo a | jxw7410 | NORMAL | 2018-12-09T07:35:54.940371+00:00 | 2018-12-09T07:35:54.940426+00:00 | 754 | false | The most intuitive way to count for 1\'s in the binary expression of a number, is counting the 1\'s. Luckily, python can do that using .count() method. \n\nSo all we have to do is convert the number to binary, and do a count(). However, how do we know if a count is prime? \n\nWe could solve for the prime, but that would take forever, instead, we can opt for a reference table of prime numbers. Therefore we create a set containing all primes from 0~19, (since 20 bits is the limit due to OP stating max number there is 10^6, which can have up to 20 bits)\n\nFrom them on, it\'s a simple comparison.\n\n```\nclass Solution:\n def countPrimeSetBits(self, L, R):\n prime_set = {2, 3, 5, 7, 11, 13, 17, 19}\n \n ret = 0\n for i in range(L, R+1):\n one_count = bin(i).count(\'1\')\n if one_count in prime_set:\n ret +=1\n \n return ret\n``` | 7 | 0 | [] | 3 |
prime-number-of-set-bits-in-binary-representation | C++ Simple Solution || 100% faster in runtime | c-simple-solution-100-faster-in-runtime-12cmy | \nclass Solution {\npublic:\n int countPrimeSetBits(int L, int R) {\n int count=0;\n for(int i=L;i<=R;i++){\n if(checkPrime(findSetB | rahuls321 | NORMAL | 2021-03-24T12:56:31.221842+00:00 | 2021-03-24T12:56:31.221887+00:00 | 1,213 | false | ```\nclass Solution {\npublic:\n int countPrimeSetBits(int L, int R) {\n int count=0;\n for(int i=L;i<=R;i++){\n if(checkPrime(findSetBits(i))) count++;\n }\n return count;\n }\n int findSetBits(int n){\n int count=0;\n while(n){\n n=n&(n-1);\n count++;\n }\n return count;\n }\n bool checkPrime(int x){\n return (x == 2 || x == 3 || x == 5 || x == 7 ||\n x == 11 || x == 13 || x == 17 || x == 19);\n }\n};\n``` | 6 | 0 | ['C', 'C++'] | 2 |
prime-number-of-set-bits-in-binary-representation | 5 lines hashset regexp javascript solution | 5-lines-hashset-regexp-javascript-soluti-zqmy | \n/**\n * @param {number} L\n * @param {number} R\n * @return {number}\n */\nvar countPrimeSetBits = function(L, R) {\n let set = new Set([2, 3, 5, 7, 11, 13, | daimant | NORMAL | 2020-03-06T12:07:46.447562+00:00 | 2020-03-06T12:07:46.447609+00:00 | 271 | false | ```\n/**\n * @param {number} L\n * @param {number} R\n * @return {number}\n */\nvar countPrimeSetBits = function(L, R) {\n let set = new Set([2, 3, 5, 7, 11, 13, 17, 19]);\n let countPrime = 0;\n \n for (let i = L; i <= R; i++) {\n if (set.has(i.toString(2).replace(/0/g, \'\').length)) countPrime++;\n }\n\n return countPrime;\n};\n``` | 6 | 0 | ['JavaScript'] | 0 |
prime-number-of-set-bits-in-binary-representation | Rust 1 liner (0ms, 1.9mb) | rust-1-liner-0ms-19mb-by-rcode0-kgm8 | \npub fn count_prime_set_bits(l: i32, r: i32) -> i32 {\n (l..=r).filter(|x|[2,3,5,7,11,13,17,19].contains(&x.count_ones())).count() as i32\n}\n// 2021 De | rcode0 | NORMAL | 2019-08-04T08:54:43.365401+00:00 | 2021-12-03T12:50:53.346746+00:00 | 289 | false | ```\npub fn count_prime_set_bits(l: i32, r: i32) -> i32 {\n (l..=r).filter(|x|[2,3,5,7,11,13,17,19].contains(&x.count_ones())).count() as i32\n}\n// 2021 Dec: Updated from 2.3->1.9mb and to not check >19 as per BigMih\'s comment\n```\n\nFun fact:\nThere\'s an instruction in recent Intel & AMD processors for counting the number of bits set in an integer:\nhttps://en.wikipedia.org/wiki/SSE4#POPCNT_and_LZCNT\n\nOften people still write loops manually to do this, but compilers can be smart enough to replace your loop with the single instruction:\nhttps://lemire.me/blog/2016/05/23/the-surprising-cleverness-of-modern-compilers/ | 6 | 0 | [] | 1 |
prime-number-of-set-bits-in-binary-representation | C++ 9 ms | c-9-ms-by-huahualeetcode-1c52 | \nclass Solution {\npublic:\n int countPrimeSetBits(int L, int R) {\n int ans = 0;\n unsigned magic = 2693408941;\n for (int n = L; n <= R; ++n)\n | huahualeetcode | NORMAL | 2018-01-18T06:48:01.131000+00:00 | 2018-10-09T13:05:07.937941+00:00 | 1,470 | false | ```\nclass Solution {\npublic:\n int countPrimeSetBits(int L, int R) {\n int ans = 0;\n unsigned magic = 2693408941;\n for (int n = L; n <= R; ++n)\n if (magic & (1 << __builtin_popcountll(n))) ++ans;\n return ans;\n }\n};\n``` | 6 | 1 | [] | 3 |
prime-number-of-set-bits-in-binary-representation | DP and Combinatorics | Fastest | O(log2(R)) | Complete math explanation | dp-and-combinatorics-fastest-olog2r-comp-mx6n | Dont forget to upvote if you like the content below. \uD83D\uDE43\n\n# TL;DR\nTake as an example the range [6, 10].\n1. Examine the most significant bit of the | wallandteen | NORMAL | 2023-02-04T22:21:17.515184+00:00 | 2023-05-07T22:10:43.087817+00:00 | 789 | false | Dont forget to upvote if you like the content below. \uD83D\uDE43\n\n# TL;DR\nTake as an example the range `[6, 10]`.\n1. Examine the most significant bit of the binary representation of $$10$$: `1010`.\n2. For numbers less than `1000` (i.e., 8 in decimal), i.e., in the range of `[0, 111]`, we can fill the $$3$$ bits with $$3$$ or $$2$$ ones. So, the count in this range is $$\\binom{3}{3}+\\binom{3}{2} = 4$$, where $$\\binom{n}{k}$$ denotes the binomial coefficient, i.e., $$\\frac{n!}{k!(n - k)!}$$.\n3. Move to the next $$1$$ and count the numbers in the range `[1000, 1010]`. We can fill the $$1$$ bit with $$1$$ one (because we already "set" $$1$$ at the beginning, making the total number of ones $$2$$, and $$2$$ is prime). Thus, the count is $$\\binom{1}{1} = 1$$.\n4. Add the counts from steps 2 and 3 to find the total count of numbers with prime set bits between `0` and `10` exclusively: $$\\binom{3}{3}+\\binom{3}{2} + \\binom{1}{1} = 5$$.\n5. Check is the original number has prime bits set *(yes, it does)*, and include it also. Now the **desired number** for the range `[0, 10]` is $$5 + 1 = 6$$.\n5. Doing the same thing for `[0, 5]` we\'ll get $$2$$.\n6. Finally, to find the count of numbers with prime set bits in the range `[6, 10]`, subtract the count for `[0, 5]` from the count for `[0, 10]`: $$6 - 2 = 4$$.\n\n\n\n# Readme\nIn the next section, I will provide a more comprehensive explanation of the thoughts behind the solution, including the mathematical reasoning and logic. If you notice any mistakes or would like to suggest improvements, please let me know in the comments. \n\n# Intuition\n\nThe goal of this task is to count the number of integers in the range `[left, right]` with a prime number of set bits in their binary representation. Instead of iterating through all integers in the range and checking the set bits one by one, we can use combinatorics and dynamic programming to solve this problem more efficiently.\n\nTo do this, we\'ll calculate the amount of desired numbers from 0 to `right` inclusively and from 0 to `left` exclusively, and then subtract the latter from the former.\n\n## Mathematical Explanation\n\nLet\'s gather some facts.\n\nIf we had a function $$f(x)$$ for $$x \\in \\mathbb{N}$$ which calculates the amount of desired numbers from $$0$$ to $$x$$ inclusively, then a count of these numbers in range $$[a,b]$$ for $$a \\in \\mathbb{N}$$, and $$b \\in \\mathbb{N}$$, and $$b \\ge a$$ would be $$f(b) - f(a - 1)$$, that\'s pretty clear.\n\nWe may notice that for numbers like $$10..0$$ having $$n$$ zeroes after the first $$1$$ the answer is just a sum of amounts of opportunities to put prime amounts of $$1$$ in $$n$$ places. These numbers are just powers of $$2$$, and this amount of opportunities is $$nCk$$, or $$\\binom{n}{k}$$ *(binomial coefficient)*, and $$\\binom{n}{k} = \\frac{n!}{k! * (n - k)!}$$, where $$n \\in \\mathbb{N}$$, in our case, is the number of places to put $$1$$ and $$k \\in \\mathbb{N}$$ is the amount of $$1$$ we are trying to put in them, and $$n \\ge k \\ge 0$$. This is because the numer itself is definetely doesn\'t count because it has only 1 *(not prime)* bit set, and with these $$nCk$$ we will check all numbers less than this one.\n\nWe can not use $$nCk$$ as is because in our case $$k$$ could possible be greater than $$n$$, so let\'s define a simple function $$c(n, k)$$ that calculates the binomial coefficient when $$n \\ge k$$ and returns 0 otherwise:\n $$c(n, k) = \\begin{cases}0,&\\text{if } n < k\\\\\\binom{n}{k}, &\\text{otherwise} \\end{cases}$$\n\nBut we also want these $$k$$ to be only primes ($$k \\in \\mathbb{P}$$). So let\'s assume we had a prime-checking function:\n $$p(x) = \\begin{cases}1,&\\text{if } x \\in \\mathbb{P}\\\\0, &\\text{otherwise} \\end{cases}$$\nSo we say that $$f(2^n) = \\Sigma_{k=0}^n (p(k) * c(n, k))$$\n\nCongratulations, now we\'re able to calculate the amount of numbers containing prime amount of set bits in their binary representation from $$0$$ to $$2^n$$. \uD83E\uDD73\n\nBut what about numbers which are not powers of 2? Well, the good news are, as we all know, all numbers are just sums of different powers of 2! Does that mean that we can just decompose any number into it\'s sum of powers of 2 and sum all values of $$f$$ on them? No, unfortunately, not that easy.\n \nConsider a number, for example, $$10100$$. It\'s obvious that we can not just do $$f(2^4) + f(2^2)$$, because $$f(2^4)$$ already counted all values from $$f(2^2)$$... Wait, was all of that a way to nowhere then?.. No! But we must to make our function a little bit more complex. For the second iteration the amount of $$1$$ to put will be 1 less because we already put one in our number and we can not to avoid of counting it. Now we say that $$f(2^n, x)=\\sum_{k=0}^n (p(k) * c(n, k - x))$$ for $$x \\in \\mathbb{N}$$, which is a number of already set bits, and $$n \\in \\mathbb{N}$$.\n\nOoof... Maybe now it\'s all done and we can solve it with that sum of values of $$f$$ by our degrees?.. Well, almost. Don\'t forget to check the number itself if it has prime set bits. \uD83C\uDF1A\n\nFinally, to find the number of desired numbers in the range $$[left, right]$$, apply the above steps for $$right$$ and $$left - 1$$, and then subtract the latter from the former:\n\n$$f(right) - f(left - 1)$$\n\nThat\'s it! This is the complete mathematical explanation of the problem and its solution. Using this approach, we can efficiently count the number of integers with a prime number of set bits in their binary representation for the given range.\n\n# Implementation\n\nLet\'s break down the code into its main components and explain the logic behind each part.\n\n## Helper Functions\n\n### nChooseK\n\nThis function calculates the binomial coefficient $$C(n, k)$$, which is used to find the number of ways to choose $$k$$ items from a set of $$n$$ items. The function uses memoization to store previously computed values in a 2D array `nChooseKCache` to avoid redundant calculations.\n\nThe function also uses the property $$C(n, k) = C(n, n - k)$$ to reduce the number of calculations needed.\n\n### isPrime\n\nThis function checks if a given number is a prime number by comparing it against the precomputed list of prime numbers `primes`.\n\n### primeBitNumbersCount\n\nThis function calculates the number of integers with a prime number of set bits in their binary representation between $$0$$ and a given number `number` (inclusive).\n\n1. The function calculates the length of the binary representation of the given number (ignoring the most significant bit, which is always $$1$$) using the formula: $$length = \\lfloor \\log_2(number) \\rfloor$$\n2. It initializes a `pointer` variable as a power of $$2$$ equal to the length of the binary representation of the given number.\n3. It iterates through the bits of the given number using a while loop. If the current bit is set ($$1$$), it calculates the number of desired numbers for the remaining bits using the `nChooseK` function and adds the result to the `primeBitsNumbersCount` variable. It then increments the `setBitsCount` variable.\n4. After iterating through all bits, the function checks if the total number of set bits is prime. If it is, it increments the `primeBitsNumbersCount`.\n\n## countPrimeSetBits\n\nThis is the main function of the solution. It calculates the number of integers with a prime number of set bits in their binary representation in the range $$[left, right]$$ by invoking the `primeBitNumbersCount` function for `right` and `left - 1`, and then subtracting the latter from the former.\n\n# Complexity\n- Time complexity of the given code is $$O(log\xB2(right) * P)$$, where $$P$$ is the number of prime numbers used in the algorithm. In this specific case, $$P = 11$$, as there are $$11$$ prime numbers in the primes array.\n - The `countPrimeSetBits` function calls `primeBitNumbersCount` twice.\n - The `primeBitNumbersCount` function has a while loop that iterates $$log\u2082(right)$$ times in the worst case, as the position variable starts at $$31$$ and decrements in each iteration until it reaches $$0$$. In each iteration, the function calls `primeBitNumbersCount(position - 1, bitsSet)` method, which has an inner loop that iterates over all the prime numbers in the primes array, i.e., $$P$$ times.\n - As a result, the time complexity is $$O(log\xB2(right) * P)$$.\n- Space complexity of the code is $$O(1)$$, because the only significant data structures used are the primes array and cache, which have a constant size.\n\n\n# Code\n```java\nclass Solution {\n\n private final int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};\n private final int[][] nChooseKCache = new int[32][32];\n\n private int nChooseK(int n, int k) {\n if (n < 0 || k < 0) {\n return 0;\n }\n k = Math.min(k, n - k); // C(n, k) = C(n, n - k)\n if (k == 0 || k == n) {\n return 1;\n }\n if (nChooseKCache[n][k] != 0) {\n return nChooseKCache[n][k];\n }\n nChooseKCache[n][k] = nChooseK(n - 1, k - 1) + nChooseK(n - 1, k);\n return nChooseKCache[n][k];\n }\n\n private boolean isPrime(int number) {\n int i = 0;\n while (primes[i] < number) {\n i++;\n }\n return primes[i] == number;\n }\n\n private int primeBitNumbersCount(int number) {\n int length = (int) (Math.log(number) / Math.log(2));\n int pointer = 1 << length;\n int setBitsCount = 0;\n int primeBitsNumbersCount = 0;\n\n while (pointer != 0) {\n if ((number & pointer) > 0) {\n for (int i = 0; i < primes.length && primes[i] - setBitsCount <= length; i++) {\n primeBitsNumbersCount += nChooseK(length, primes[i] - setBitsCount);\n }\n setBitsCount++;\n }\n pointer >>>= 1;\n length--;\n }\n\n if (isPrime(setBitsCount)) {\n primeBitsNumbersCount++;\n }\n\n return primeBitsNumbersCount;\n }\n\n public int countPrimeSetBits(int left, int right) {\n return primeBitNumbersCount(right) - primeBitNumbersCount(left - 1);\n }\n}\n```\n | 5 | 0 | ['Math', 'Dynamic Programming', 'Brainteaser', 'Combinatorics', 'Java'] | 0 |
prime-number-of-set-bits-in-binary-representation | java FOR LOOP easy SOLUTION 👌 | java-for-loop-easy-solution-by-sulaymon-fgorf | \n public int countPrimeSetBits(int left, int right) {\n int res = 0;\n for (int i = left; i <= right; i++) {\n if (isPrime(Integer. | Sulaymon-Dev20 | NORMAL | 2022-05-26T10:37:47.418513+00:00 | 2022-05-26T10:37:47.418545+00:00 | 735 | false | ```\n public int countPrimeSetBits(int left, int right) {\n int res = 0;\n for (int i = left; i <= right; i++) {\n if (isPrime(Integer.bitCount(i))) res++;\n }\n return res;\n }\n\n public boolean isPrime(int n) {\n if (n <= 1) return false;\n for (int i = 2; i < Math.sqrt(n); i++) {\n if (n % i == 0) return false;\n }\n return true;\n }\n``` | 5 | 1 | ['Java'] | 2 |
prime-number-of-set-bits-in-binary-representation | Python Solution w/o bit manipulation, 214ms beats 91.23% with Explanation | python-solution-wo-bit-manipulation-214m-kzmv | Explanation\nThe hard part was checking whether the set bit was prime, but the 32-bit integer limit helped us with that! \uD83D\uDE0F\n\n1. Iterate through the | alexl5311 | NORMAL | 2022-05-09T03:54:18.910591+00:00 | 2022-05-09T03:54:18.910619+00:00 | 578 | false | **Explanation**\n*The hard part was checking whether the set bit was prime, but the 32-bit integer limit helped us with that! \uD83D\uDE0F*\n\n1. Iterate through the range\n2. Check the number of `1`\'s in the binary representation of that the number\n3. Check if it is prime: if yes, add 1 to count\n\n\n\n\n```\nclass Solution(object):\n def countPrimeSetBits(self, left, right):\n """\n :type left: int\n :type right: int\n :rtype: int\n """\n count = 0\n primes = [2,3,5,7,11,13,17,19,23,29,31]\n for i in range(left, right+1):\n set_bits = bin(i).count(\'1\')\n if set_bits in primes:\n count += 1 \n return count\n```\n\n**If you liked this, please upvote to support me!** | 5 | 0 | ['Python'] | 0 |
prime-number-of-set-bits-in-binary-representation | python 1 line solution | python-1-line-solution-by-jason003-zset | python\nreturn len([i for i in range(L, R + 1) if bin(i).count(\'1\') in {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}])\n | jason003 | NORMAL | 2019-02-20T14:45:58.347720+00:00 | 2019-02-20T14:45:58.347760+00:00 | 391 | false | ```python\nreturn len([i for i in range(L, R + 1) if bin(i).count(\'1\') in {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}])\n``` | 5 | 0 | [] | 0 |
prime-number-of-set-bits-in-binary-representation | O(log R) solution (C++, Python, Ruby) | olog-r-solution-c-python-ruby-by-stefanp-5kto | So far I think only brute force solutions have been posted (checking all numbers from L to R and counting the "good" ones (those with a prime number of 1-bits)) | stefanpochmann | NORMAL | 2018-01-14T20:29:59.761000+00:00 | 2018-01-14T20:29:59.761000+00:00 | 866 | false | So far I think only brute force solutions have been posted (checking all numbers from L to R and counting the "good" ones (those with a prime number of 1-bits)). Here's an efficient solution, it's O(log<sup>2</sup> R<sub>max</sub>) where R<sub>max</sub> is the maximum allowed R-value (i.e., 10^6 in the problem specification). And in the end I optimize it to O(log R).\n\nEven the Python version can for example solve `countPrimeSetBits(1, 1000000)` (much larger range than allowed in the problem) in about 0.00006 seconds on my PC. And `countPrimeSetBits(None, 1, 1000000000)` in about 0.00015 seconds (after modifying the code to go up to bit 29 instead of just bit 19).\n\nFirst let's reduce the "from-to" problem to an "under" problem: How to count the "good" numbers from L to R? Count those under R+1 and discount those under L.\n\nTo count the "good" numbers under a certain limit: How do numbers under the limit look like? They may start like the limit (i.e., have the same high-bits) but then some 1-bit must be changed to a 0-bit. And then the lower bits can be whatever.\n\nSo go through the bits of the limit number. Whenever we see a 1-bit, we can make it 0 and then have to ask: With all the possibilities for the remaining lower bits, how many of them give us numbers with a prime number of 1-bits? Well, let's say 5 of the higher bits are 1-bits and we have 7 lower bits left. We can turn 0 to 7 of them into 1-bits. But together with the 5 higher 1-bits we want a prime number, so exactly 0, 2, or 6 of the lower bits must be 1-bits (only 5+0, 5+2 and 5+6 are prime). And for example for 2 lower 1-bits, we have 7C2 ("7 choose 2") possibilities to choose 2 of those 7 lower bits.\n\n```\nclass Solution {\npublic:\n int countPrimeSetBits(int L, int R) {\n return under(R+1) - under(L);\n }\n\n int under(int limit) {\n int count = 0, highOnes = 0;\n for (int lowBits = 19; lowBits >= 0; lowBits--) {\n if (limit & (1 << lowBits)) {\n for (int lowOnes = 0; lowOnes <= lowBits; lowOnes++)\n if (isPrime(lowOnes + highOnes))\n count += nCk(lowBits, lowOnes);\n highOnes++;\n }\n }\n return count;\n }\n\n int isPrime(int n) {\n return n < 4 ? n > 1 : n % 2 && n % 3;\n }\n \n int nCk(int n, int k) {\n return k < 0 ? 0 : k == 0 ? 1 : nCk(n, k-1) * (n-k+1) / k;\n }\n};\n```\nOptimized version which doesn't recompute nCk from scratch all the time:\n```\nclass Solution {\npublic:\n int countPrimeSetBits(int L, int R) {\n return under(R+1) - under(L);\n }\n\n int under(int m) {\n int count = 0, K = 0;\n for (int n = 19; n >= 0; n--) {\n if (m & (1 << n)) {\n for (int k = 0, nCk = 1; k <= n; k++, nCk = nCk * (n-k+1) / k)\n if (isPrime(k + K))\n count += nCk;\n K++;\n }\n }\n return count;\n }\n\n int isPrime(int n) {\n return n < 4 ? n > 1 : n % 2 && n % 3;\n }\n};\n```\nHere `K` is the number of 1-bits in the upper part (above the found 1-bit), `n` is the number of bits in the lower part (below the found 1-bit), and `k` is the number of 1-bits in the lower part.\n\nThe solution could be further optimized to O(log R<sub>max</sub>) by replacing the inner loop with a table lookup: `count += lookup[K][n]`. Since 0 ≤ `K`, `n` ≤ 19, this would be a fairly small table that could easily be hardcoded (or just computed once and stored in a static variable).\n\n\nPython version:\n\n def countPrimeSetBits(self, L, R):\n def under(m):\n count = 0\n K = 0;\n for n in range(19, -1, -1):\n if m & (1 << n):\n nCk = 1\n for k in range(n+1):\n if k + K in {2, 3, 5, 7, 11, 13, 17, 19}:\n count += nCk\n nCk = nCk * (n-k) / (k+1)\n K += 1\n return count\n return under(R+1) - under(L)\n\nRuby version:\n```\ndef count_prime_set_bits(l, r)\n def under(m)\n count = 0\n hi = 0;\n 19.downto(0) do |n|\n if m & (1 << n) > 0\n nCk = 1\n (0..n).each do |k|\n count += nCk if [2, 3, 5, 7, 11, 13, 17, 19].member?(k + hi)\n nCk = nCk * (n-k) / (k+1)\n end\n hi += 1\n end\n end\n count\n end\n under(r+1) - under(l)\nend\n```\n\n## Optimization to O(log R)\nWith the precomputed lookup table mentioned above, and I don't always start at bit 19 but just at the highest actual 1-bit:\n```\nlookup = [[0, 0, 1, 4, 10, 21, 41, 78, 148, 282, 537, 1013, 1882, 3446, 6267, 11468, 21416, 41209, 81771, 166042], [0, 1, 3, 6, 11, 20, 37, 70, 134, 255, 476, 869, 1564, 2821, 5201, 9948, 19793, 40562, 84271, 174952], [1, 2, 3, 5, 9, 17, 33, 64, 121, 221, 393, 695, 1257, 2380, 4747, 9845, 20769, 43709, 90681, 184624], [1, 1, 2, 4, 8, 16, 31, 57, 100, 172, 302, 562, 1123, 2367, 5098, 10924, 22940, 46972, 93943, 184605], [0, 1, 2, 4, 8, 15, 26, 43, 72, 130, 260, 561, 1244, 2731, 5826, 12016, 24032, 46971, 90662, 174762], [1, 1, 2, 4, 7, 11, 17, 29, 58, 130, 301, 683, 1487, 3095, 6190, 12016, 22939, 43691, 84100, 164902], [0, 1, 2, 3, 4, 6, 12, 29, 72, 171, 382, 804, 1608, 3095, 5826, 10923, 20752, 40409, 80802, 164749], [1, 1, 1, 1, 2, 6, 17, 43, 99, 211, 422, 804, 1487, 2731, 5097, 9829, 19657, 40393, 83947, 173775], [0, 0, 0, 1, 4, 11, 26, 56, 112, 211, 382, 683, 1244, 2366, 4732, 9828, 20736, 43554, 89828, 180557], [0, 0, 1, 3, 7, 15, 30, 56, 99, 171, 301, 561, 1122, 2366, 5096, 10908, 22818, 46274, 90729, 172007], [0, 1, 2, 4, 8, 15, 26, 43, 72, 130, 260, 561, 1244, 2730, 5812, 11910, 23456, 44455, 81278, 143754], [1, 1, 2, 4, 7, 11, 17, 29, 58, 130, 301, 683, 1486, 3082, 6098, 11546, 20999, 36823, 62476, 102886], [0, 1, 2, 3, 4, 6, 12, 29, 72, 171, 382, 803, 1596, 3016, 5448, 9453, 15824, 25653, 40410, 62035], [1, 1, 1, 1, 2, 6, 17, 43, 99, 211, 421, 793, 1420, 2432, 4005, 6371, 9829, 14757, 21625, 31009], [0, 0, 0, 1, 4, 11, 26, 56, 112, 210, 372, 627, 1012, 1573, 2366, 3458, 4928, 6868, 9384, 12597], [0, 0, 1, 3, 7, 15, 30, 56, 98, 162, 255, 385, 561, 793, 1092, 1470, 1940, 2516, 3213, 4047], [0, 1, 2, 4, 8, 15, 26, 42, 64, 93, 130, 176, 232, 299, 378, 470, 576, 697, 834, 988], [1, 1, 2, 4, 7, 11, 16, 22, 29, 37, 46, 56, 67, 79, 92, 106, 121, 137, 154, 172], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]]\n\nclass Solution(object):\n def countPrimeSetBits(self, L, R):\n def under(m):\n count = 0\n K = 0;\n for n in range(m.bit_length())[::-1]:\n if m & (1 << n):\n count += lookup[K][n]\n K += 1\n return count\n return under(R+1) - under(L)\n```\nFor `countPrimeSetBits(1, 1000000)` this takes only about 0.0000045 seconds on my PC. | 5 | 1 | [] | 1 |
prime-number-of-set-bits-in-binary-representation | C++ Bits count vs Combinatorial Formula(Pascal)||Beats 100% | c-bits-count-vs-combinatorial-formulapas-ffy8 | \n# Intuition\n Describe your first thoughts on how to solve this problem. \nBits counting is very intuitive to solve this question and just uses built-in func | anwendeng | NORMAL | 2023-09-02T05:41:23.153073+00:00 | 2023-09-02T05:41:23.153095+00:00 | 320 | false | \n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBits counting is very intuitive to solve this question and just uses built-in function. The hard way is to use the follolwing combinatorial formula\n$$\n#\\{x <N|bit\\_count(x)=k\\} =\n\\sum_{i=0}^k C(p[i], k-i)\n$$\nwhere p[i]=position for i-th 1 in N\'s binary expression. The combinatorial numbers $C(N,k)$ are computed by Pascal\'s traingle, i.e.\n$\nC(N, k)=C(N-1, k-1)+C(N-1, k) \n$ for $N\\geq k.$\n[Please turn on English subtitles if necessary]\n[https://youtu.be/paoJGMYEEhA?si=QM8YR8CCCTjLXqsA](https://youtu.be/paoJGMYEEhA?si=QM8YR8CCCTjLXqsA)\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe question asks the how many numbers $x\\in [left, right]$ for which bit_count(x) is a prime. \n\nSince the constraints \n```\n1 <= left <= right <= 10^6\n0 <= right - left <= 10^4\n```\nare so small, a list of primes below 20 is enough, and the bit-length is not greater than 20. Pascal traingle needs just a small memory need! \n```\nint prime[] = {2, 3, 5, 7, 11, 13, 17, 19};\nint C[21][21] = {0};\n```\nSome functions are written:\n```\nvoid PascalTriangle(int n)=> compute C\nvector<int> N2p(int N) => convert N to array p\nint nums_bitcount(vector<int>& p, int k) =>combinatorial formula\nint nums_bitcount_isPrime(int N) => summing all k being prime\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\neasy Bits counting method: $O(n\\log n)$ \nhard Combinatorial Formula method $O(\\log^2 n)$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(\\log n)$ vs $O(\\log^2 n)$\n# Hard approach using combinatorial formula beats 100% runtime 0 ms\n```\n/*\nThere is a combinatorial formula for computing \n#{x <N| x is natural number with bitcount(x)=k} =\n\\sum_{i=0}^k C(p[i], k-i)\nwhere p[i]=position for i-th 1 in N\'s binary expression.\n*/\n\nint prime[] = {2, 3, 5, 7, 11, 13, 17, 19};\nint C[21][21] = {0};\n\nclass Solution {\npublic:\n void PascalTriangle(int n) {\n for (int i = 0; i <= n; i++) {\n fill(C[i], C[i] + (i + 1), 1);\n for (int j = 1; j <= i / 2; j++) {\n C[i][i-j] = C[i][j] = C[i-1][j-1] + C[i-1][j];\n }\n }\n }\n\n vector<int> N2p(int N) {\n bitset<21> bN(N);\n vector<int> p;\n for (int i=20; i >= 0; i--) {\n if (bN[i]) p.push_back(i);\n }\n return p;\n }\n\n int nums_bitcount(vector<int>& p, int k) {\n int sum = 0;\n for (int i = 0; i < p.size(); i++) {\n int maxIndex = min(p[i], k-i);\n if (maxIndex >= 0) {\n sum += C[p[i]][k-i];\n }\n }\n return sum;\n }\n\n int nums_bitcount_isPrime(int N) {\n vector<int> p = N2p(N);\n int sum = 0;\n for (int k : prime) {\n sum += nums_bitcount(p, k);\n }\n return sum;\n }\n\n int countPrimeSetBits(int left, int right) {\n int L = log2(right+1) + 1;\n PascalTriangle(L);\n return nums_bitcount_isPrime(right+1)-nums_bitcount_isPrime(left);\n }\n};\n```\n# easy approach beats 100% runtime 0 ms\n\n```\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int prime[]={2, 3, 5, 7, 11, 13, 17, 19};\n vector<bool> isPrime(21, 0);\n for(int p: prime) isPrime[p]=1;\n int sum=0;\n for(int i=left; i<=right; i++){\n int b=__builtin_popcount(i);\n if (isPrime[b]) sum++;\n }\n return sum;\n }\n};\n``` | 4 | 0 | ['Dynamic Programming', 'Combinatorics', 'Number Theory', 'C++'] | 0 |
prime-number-of-set-bits-in-binary-representation | Simple C++ Code with Explanation || Easy understanding | simple-c-code-with-explanation-easy-unde-y8gs | class Solution {\npublic:\nint countPrimeSetBits(int left, int right) {\n// given constraint left , right <= 10^6\n\n // 2^10 == 10^3 implies 10^6 ==2^20 ( | codevin6 | NORMAL | 2023-02-17T18:11:03.001978+00:00 | 2023-02-17T18:11:03.002012+00:00 | 597 | false | class Solution {\npublic:\nint countPrimeSetBits(int left, int right) {\n// given constraint left , right <= 10^6\n\n // 2^10 == 10^3 implies 10^6 ==2^20 ( 20 bits can be set at max )\n \n vector<bool> p(20,false);\n \n //set prime vector p\n p[2]=p[3]=p[5]=p[7]=p[11]=p[13]=p[17]=p[19]=true;\n \n int result=0;\n\n for(int i=left;i<right+1;i++)\n {\n int t=i,c=0;\n while(t)\n {\n c=c+(t&1);\n t=t>>1;\n }\n \n if(p[c]==true)\n result++;\n }\n return result;\n}\n}; | 4 | 0 | ['C'] | 1 |
prime-number-of-set-bits-in-binary-representation | C++ 3ms | c-3ms-by-iamssuraj-seak | \n```\nclass Solution {\npublic:\n int cnt1(int n)\n {\n int cnt = 0;\n while(n)\n {\n n = n & (n-1);\n cnt++;\ | iamssuraj | NORMAL | 2022-08-12T05:41:34.873746+00:00 | 2022-08-12T05:45:17.797223+00:00 | 201 | false | \n```\nclass Solution {\npublic:\n int cnt1(int n)\n {\n int cnt = 0;\n while(n)\n {\n n = n & (n-1);\n cnt++;\n }\n return cnt;\n }\n bool isPrime(int n)\n {\n return n == 2 || n ==3 || n == 5 || n == 7 || n == 11 || n == 13 || n == 17 || n == 19;\n // max value in the question is 10^6 boils down to 2^19 (approx), so at max there can be only 19 set bits\n }\n int countPrimeSetBits(int left, int right) {\n int cnt = 0;\n for(int i=left;i<=right;i++)\n {\n if(isPrime(cnt1(i)))\n {\n cnt++;\n }\n }\n return cnt;\n }\n}; | 4 | 0 | [] | 0 |
prime-number-of-set-bits-in-binary-representation | C++| EASY TO UNDERSTAND| fast and efficient | Intuitive approach | c-easy-to-understand-fast-and-efficient-p6rf1 | Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\n```\nclass Solution {\npublic:\n int countPrimeSetBits(int le | aarindey | NORMAL | 2021-06-05T17:56:31.937848+00:00 | 2021-06-24T23:19:01.358436+00:00 | 519 | false | **Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)**\n```\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int num;\n int count,c=0;\n while(left!=(right+1)) \n {\n count=0;\n num=left;\n while(num)\n {\n count++;\n num=num&(num-1);\n } \n if(prime(count))\n c++;\n left++;\n } \n return c;\n }\nbool prime(int num)\n{\n int c=0;\n for(int i=num;i>=1;i--)\n {\n if(num%i==0)\n c++; \n } \n return c==2;\n} \n}; | 4 | 0 | ['Bit Manipulation', 'C'] | 2 |
prime-number-of-set-bits-in-binary-representation | easy python again | easy-python-again-by-bor4eg-dkg2 | class Solution:\n \n def countPrimeSetBits(self, left: int, right: int) -> int:\n res = 0\n for x in range(left, right+1):\n if | bor4eg | NORMAL | 2021-05-30T11:22:26.172400+00:00 | 2021-05-30T12:48:05.954369+00:00 | 100 | false | class Solution:\n \n def countPrimeSetBits(self, left: int, right: int) -> int:\n res = 0\n for x in range(left, right+1):\n if bin(x).count(\'1\') in {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}:\n res += 1\n return res\n | 4 | 0 | [] | 1 |
prime-number-of-set-bits-in-binary-representation | simple java solution: time O(n), space O(1) | simple-java-solution-time-on-space-o1-by-z1or | Intuition:\nWe have limited range of L and R - up to 10^6, meaning their bit representations will have up to 20 symbols (10^6 < 2^20).\nWe can cash prime number | trofimoff | NORMAL | 2020-06-21T23:13:45.902464+00:00 | 2020-06-21T23:16:09.189534+00:00 | 632 | false | **Intuition:**\nWe have limited range of L and R - up to 10^6, meaning their bit representations will have up to 20 symbols (10^6 < 2^20).\nWe can cash prime numbers in range of 0-20, maybe the most efficient is to use bucket sort so the found prime numbers: 2, 3, 5, 7, 11, 13, 17, 19 are converted into true in the corresponding array of booleans of length 21\nThe final solution looks like:\n```\npublic int countPrimeSetBits(int L, int R) {\n boolean [] primes = new boolean[]{false, false, true, true, false, true, false, true, false, false , false, true, false, true, false, false, false, true, false, true, false};\n int count = 0;\n for(int i = L; i <= R; i++) {\n if (primes[countBits(i)]) count++;\n }\n return count;\n }\n \n private int countBits(int n) {\n int count = 0;\n for(int i = n; i > 0; i >>= 1)\n count += i & 1;\n return count;\n }\n``` | 4 | 0 | ['Bucket Sort', 'Java'] | 1 |
prime-number-of-set-bits-in-binary-representation | C# Solution | c-solution-by-moh80-6rvd | public int CountPrimeSetBits(int L, int R) {\n int count = 0;\n for (int i = L; i <= R; i++)\n {\n int bitsCount = GetBitsCount( | Moh80 | NORMAL | 2018-01-15T18:36:25.903000+00:00 | 2018-01-15T18:36:25.903000+00:00 | 220 | false | public int CountPrimeSetBits(int L, int R) {\n int count = 0;\n for (int i = L; i <= R; i++)\n {\n int bitsCount = GetBitsCount(i);\n if (IsPrime(bitsCount)) count++; \n }\n \n return count; \n }\n \n private int GetBitsCount(int a)\n {\n int count = 0; \n while (a > 0)\n {\n count += a % 2;\n a /= 2; \n }\n \n return count; \n }\n \n private bool IsPrime(int a)\n {\n if (a <= 1) return false; \n \n for (int i = 2; i < a; i++)\n {\n if (a % i == 0) return false; \n }\n \n return true; \n } | 4 | 0 | [] | 0 |
prime-number-of-set-bits-in-binary-representation | 762. Simple C++ solution | 762-simple-c-solution-by-shreyash_153-kn2n | Code\n\nclass Solution {\npublic:\n bool isprime(int k)\n {\n if(k==2||k==3||k==5||k==7||k==11||k==13||k==17||k==19)\n return 1;\n el | shreyash_153 | NORMAL | 2024-05-11T10:09:32.016556+00:00 | 2024-05-11T10:09:32.016586+00:00 | 505 | false | # Code\n```\nclass Solution {\npublic:\n bool isprime(int k)\n {\n if(k==2||k==3||k==5||k==7||k==11||k==13||k==17||k==19)\n return 1;\n else\n return 0;\n }\n int countPrimeSetBits(int left, int right) {\n int ans=0;\n for(int i=left;i<=right;i++)\n {\n int num=i;\n int cnt=0;\n while(num)\n {\n num&=(num-1);\n cnt++;\n }\n if(isprime(cnt))\n ans++;\n else\n continue;\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['Math', 'C++'] | 0 |
prime-number-of-set-bits-in-binary-representation | 762: Beats 91.74%, Solution with step by step explanation | 762-beats-9174-solution-with-step-by-ste-gsob | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n\n\nWe create a set of p | Marlen09 | NORMAL | 2023-10-24T17:34:31.611226+00:00 | 2023-10-24T17:34:59.861231+00:00 | 369 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n```\n\nWe create a set of prime numbers which are less than 20. Since the maximum number of bits we are concerned with is 20 (for the given problem constraints), we only need primes below 20.\n\n```\n count = 0\n```\n\nInitialize a count to zero. This variable will keep track of how many numbers have a prime number of set bits.\n\n```\n for num in range(left, right+1):\n```\n\nWe loop through each number in the inclusive range of left to right.\n\n```\n set_bits = num.bit_count()\n```\n\nFor each number, we calculate the number of set bits (i.e., number of 1s in its binary representation). Python provides a built-in method bit_count() for integers to count the number of set bits.\n\n```\n if set_bits in primes:\n count += 1\n```\n\nIf the number of set bits is one of the prime numbers in our set, we increment our count.\n\n```\n return count\n```\nFinally, after iterating through all the numbers, we return the count.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n count = 0\n\n for num in range(left, right+1):\n\n set_bits = num.bit_count()\n\n if set_bits in primes:\n count += 1\n\n return count\n\n``` | 3 | 0 | ['Math', 'Bit Manipulation', 'Python', 'Python3'] | 0 |
prime-number-of-set-bits-in-binary-representation | Go - using Kernighan's algorithm for counting set bits | go-using-kernighans-algorithm-for-counti-qtww | \nfunc countPrimeSetBits(left int, right int) int {\n primes := map[int]bool{\n 2: true,\n 3: true,\n 5: true,\n 7: true,\n | tucux | NORMAL | 2022-09-11T16:50:00.873627+00:00 | 2022-09-11T16:50:00.873679+00:00 | 462 | false | ```\nfunc countPrimeSetBits(left int, right int) int {\n primes := map[int]bool{\n 2: true,\n 3: true,\n 5: true,\n 7: true,\n 11: true,\n 13: true,\n 17: true,\n 19: true,\n }\n c := 0\n for i := left; i <= right; i++ {\n s := countSetBits(i)\n if primes[s] {\n c++\n }\n }\n return c\n}\n\nfunc countSetBits(n int) int {\n c := 0\n for n != 0 {\n n = n & (n-1)\n c++\n }\n return c\n}\n``` | 3 | 0 | ['Go'] | 0 |
prime-number-of-set-bits-in-binary-representation | Python3 - with checkPrime() function | python3-with-checkprime-function-by-than-2fog | \nclass Solution:\n def checkPrime(self, number):\n if number > 1:\n for i in range(2, number):\n if (number % i) == 0:\n | thanhinterpol | NORMAL | 2020-10-06T08:11:50.173913+00:00 | 2020-10-06T08:11:50.173953+00:00 | 132 | false | ```\nclass Solution:\n def checkPrime(self, number):\n if number > 1:\n for i in range(2, number):\n if (number % i) == 0:\n return False\n break\n else:\n return True\n else:\n return False\n def countPrimeSetBits(self, L: int, R: int) -> int:\n return sum([self.checkPrime(bin(x)[2:].count(\'1\')) for x in range(L,R+1)])\n``` | 3 | 0 | [] | 0 |
prime-number-of-set-bits-in-binary-representation | [JavaScript] JS Solution(s) that beats 100% | javascript-js-solutions-that-beats-100-b-kfxo | My first approach was the following (it uses Primality test with 6k \xB1 1 optimization, pre-defined set of known prime numbers and caching):\n\n/**\n * @param | GreenTeaCake | NORMAL | 2019-05-23T17:58:26.912378+00:00 | 2019-05-23T17:58:26.912418+00:00 | 714 | false | My first approach was the following (it uses [Primality test with 6k \xB1 1 optimization](https://en.wikipedia.org/wiki/Primality_test#Pseudocode), pre-defined set of known prime numbers and caching):\n```\n/**\n * @param {number} L\n * @param {number} R\n * @return {number}\n */\nconst getNumOfSetBits = function(n) {\n let result = 0;\n while (n) {\n result += (n & 1);\n n = n >> 1;\n }\n return result;\n}\n\nconst isPrime = function(n) {\n if (n <= 1) {\n return false;\n }\n if (n <= 3) {\n return true;\n }\n if (n % 2 === 0 || n % 3 === 0) {\n return false;\n }\n for (let i = 5; i * i < n; i += 6) {\n if (n % i === 0 || n % (i + 2) === 0) {\n return false;\n }\n }\n return true;\n}\n\nconst primes = new Set([2, 3, 5, 7, 11]);\n\nconst countPrimeSetBits = function(L, R) {\n let count = 0;\n for (let n = L; n <= R; n++) {\n const bitNum = getNumOfSetBits(n);\n if (primes.has(bitNum)) {\n count++;\n } else if (isPrime(bitNum)) {\n count++;\n primes.add(bitNum);\n }\n }\n return count;\n};\n```\nBut then I found a post from [@jxw7410](https://leetcode.com/jxw7410): "[Python simple solution w/ explanation](https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/203317/Python-simple-solution-w-explanation)" and siplified the solution to:\n```\n/**\n * @param {number} L\n * @param {number} R\n * @return {number}\n */\nconst getNumOfSetBits = function(n) {\n let result = 0;\n while (n) {\n result += (n & 1);\n n = n >> 1;\n }\n return result;\n}\n\nconst primes = new Set([2, 3, 5, 7, 11, 13, 17, 19, 23]);\n\nconst countPrimeSetBits = function(L, R) {\n let count = 0;\n for (let n = L; n <= R; n++) {\n if (primes.has(getNumOfSetBits(n))) {\n count++;\n }\n }\n return count;\n};\n```\nIt is strange but the second variant shows worse results than the first one. | 3 | 0 | ['JavaScript'] | 1 |
prime-number-of-set-bits-in-binary-representation | Simple javascript | simple-javascript-by-absborodin-p24x | \n /**\n * https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/\n * @param {number} L\n * @param {number} R\n * @return {nu | absborodin | NORMAL | 2019-01-20T11:35:36.350946+00:00 | 2019-01-20T11:35:36.353913+00:00 | 255 | false | ```\n /**\n * https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/\n * @param {number} L\n * @param {number} R\n * @return {number}\n */\n var countPrimeSetBits = function(L, R) {\n let result = 0;\n let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23];\n\n for(let i = L; i <= R; i++){\n let num2 = i.toString(2);\n let count = 0;\n\n num2.split(\'\').forEach(sym => {\n if(sym == 1) count++;\n });\n\n if(primes.indexOf(count) > -1) result++;\n }\n\n return result;\n };\n ``` | 3 | 0 | [] | 1 |
prime-number-of-set-bits-in-binary-representation | Short C++, 12 ms | short-c-12-ms-by-stefanpochmann-qqby | int countPrimeSetBits(int L, int R) {\n int count = 0;\n while (L <= R) {\n int b = __builtin_popcount(L++);\n count += b < | stefanpochmann | NORMAL | 2018-01-14T05:43:07.842000+00:00 | 2018-01-14T05:43:07.842000+00:00 | 1,308 | false | int countPrimeSetBits(int L, int R) {\n int count = 0;\n while (L <= R) {\n int b = __builtin_popcount(L++);\n count += b < 4 ? b > 1 : b % 2 && b % 3;\n }\n return count;\n }\n\nNumbers in the allowed range have only up to 20 bits and for a primality check it suffices to check prime divisors until the square root, so I just test prime divisors 2 and 3. | 3 | 1 | [] | 3 |
prime-number-of-set-bits-in-binary-representation | Prime Numbers of Set Bits | prime-numbers-of-set-bits-by-kartixrivas-wgo5 | IntuitionApproachComplexity
Time complexity: O((right - left + 1) * log(right))
Space complexity: O(1)
Code | kartixrivastava | NORMAL | 2025-03-13T05:38:54.218886+00:00 | 2025-03-13T05:38:54.218886+00:00 | 77 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O((right - left + 1) * log(right))
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool isPrime(int n) {
if (n <= 1) {
return false;
}
int a = 0;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
a = 1;
break;
}
}
if (a == 0) {
return true;
} else {
return false;
}
}
int setBits(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1);
count++;
}
return count;
}
int countPrimeSetBits(int left, int right) {
int count = 0;
for (int i = left; i <= right; i++) {
if (isPrime(setBits(i))) {
count++;
}
}
return count;
}
};
``` | 2 | 0 | ['C++'] | 0 |
prime-number-of-set-bits-in-binary-representation | Counting Prime Set Bits in a Binary Range Using C++ | counting-prime-set-bits-in-a-binary-rang-avzf | Intuition\nThe problem revolves around counting the number of prime set bits in binary representations of numbers within a given range. The key insight is recog | Krishnaa2004 | NORMAL | 2024-09-07T13:47:47.993887+00:00 | 2024-09-07T13:47:47.993909+00:00 | 250 | false | # Intuition\nThe problem revolves around counting the number of prime set bits in binary representations of numbers within a given range. The key insight is recognizing that the set bit count can only be prime if it matches one of the known small prime numbers.\n\n# Approach\n1. **Prime Check**: Implement a helper function `prime` that checks if a number is one of the small prime numbers (since the maximum set bit count for any integer is quite small).\n2. **Set Bit Count**: Implement a `setBits` function to count the number of set bits (1s) in the binary representation of a number.\n3. **Iterate Through Range**: Iterate through the numbers in the given range `[left, right]`. For each number, count its set bits and check if this count is a prime number.\n4. **Count Primes**: Increment the count if the set bit count is prime.\n\n# Complexity\n- **Time complexity**: $$O(n \\cdot \\log m)$$ where $$n$$ is the number of integers in the range, and $$m$$ is the maximum number in the range (as calculating set bits takes $$O(\\log m)$$ time).\n- **Space complexity**: $$O(1)$$ since we are using a fixed amount of extra space.\n\n# Code\n```cpp\nclass Solution {\npublic:\n bool prime(int n) {\n return n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 || n == 17 || n == 19;\n }\n \n int setBits(int n) {\n int count = 0; \n while (n > 0) {\n count += n % 2;\n n >>= 1;\n }\n return count; \n }\n \n int countPrimeSetBits(int left, int right) {\n int count = 0; \n for (int i = left; i <= right; ++i) {\n if (prime(setBits(i))) {\n count++;\n }\n }\n return count; \n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
prime-number-of-set-bits-in-binary-representation | Easy Java Solution | easy-java-solution-by-parth_dhavan-ifr7 | Intuition\n Describe your first thoughts on how to solve this problem. \nBinary Representation: Any integer can be represented in binary form, consisting of 0s | Parth_Dhavan | NORMAL | 2024-06-24T20:53:06.490837+00:00 | 2024-06-24T20:53:06.490865+00:00 | 325 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBinary Representation: Any integer can be represented in binary form, consisting of 0s and 1s.\nSet Bits: The number of 1s in the binary representation is referred to as the count of set bits.\nPrime Numbers: A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.\nObjective: For each number in the given range, count its set bits and check if this count is a prime number.\n\n\n# Approach\nIterate Through Range: Iterate through each number from left to right.\nCount Set Bits: For each number, calculate the number of set bits using a helper function (hammingWeight).\nPrime Check: Check if the number of set bits is prime using another helper function (isPrime).\nCount Primes: Maintain a count of numbers that have a prime number of set bits.\n\n\n\n# Code\n```\nclass Solution {\n public int countPrimeSetBits(int left, int right) {\n int ans=0;\n int c=0;\n boolean res=false;\n\n for(int i=left;i<=right;i++){\n ans=hammingWeight(i);\n \n res=isPrime(ans);\n\n if(res==true){\n c++;\n }\n }\n return c;\n \n }\n public int hammingWeight(int n) {\n int c=0;\n while(n>0){\n if((n & 1)==1){\n c++;\n }\n n=n>>1;\n \n }\n return c;\n }\n\n static boolean isPrime(int n)\n {\n // Corner case\n if (n <= 1)\n return false;\n \n // Check from 2 to n-1\n for (int i = 2; i < n; i++)\n if (n % i == 0)\n return false;\n \n return true;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
prime-number-of-set-bits-in-binary-representation | Easy to Understand || Well defined clean code | easy-to-understand-well-defined-clean-co-ju6l | 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 | Anshika_Srivastava | NORMAL | 2024-06-24T20:49:40.630042+00:00 | 2024-06-24T20:49:40.630065+00:00 | 289 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int countPrimeSetBits(int left, int right) {\n int count = 0;\n for(int i=left;i<=right;i++)\n {\n int setB = countSetBits(i);\n if(isPrime(setB))\n count++;\n }\n return count;\n }\n\n\n int countSetBits(int n) {\n int c=0;\n while(n>0){\n if((n & 1)==1)\n c++;\n n=n>>1; \n }\n return c;\n }\n\n boolean isPrime(int n)\n {\n if (n <= 1)\n return false;\n\n for (int i = 2; i < n; i++)\n if (n % i == 0)\n return false;\n \n return true;\n } \n}\n``` | 2 | 0 | ['Bit Manipulation', 'Java'] | 0 |
prime-number-of-set-bits-in-binary-representation | Easiest 6 languages C++ / Python3 / Java / C / Python beats 100% | easiest-6-languages-c-python3-java-c-pyt-22sm | Intuition\n\n\n\n\nC++ []\nclass Solution {\nprivate:\n bool isPrime(int n) {\n if (n == 1)\n return false;\n for (int i = 2; i <= n | Edwards310 | NORMAL | 2024-03-09T11:37:42.299854+00:00 | 2024-03-09T11:37:42.299883+00:00 | 294 | false | # Intuition\n\n\n\n\n```C++ []\nclass Solution {\nprivate:\n bool isPrime(int n) {\n if (n == 1)\n return false;\n for (int i = 2; i <= n / 2; i++)\n if (n % i == 0)\n return false;\n return true;\n }\n\npublic:\n int countPrimeSetBits(int left, int right) {\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n int cnt = 0;\n for (int i = left; i <= right; i++) {\n int bits = __builtin_popcount(i);\n if (isPrime(bits))\n cnt++;\n }\n return cnt;\n }\n};\n```\n```python3 []\nclass Solution:\n def countPrimeSetBits(self, L: int, R: int) -> int:\n res = 0\n for i in range(L, R+1):\n bits = bin(i).count(\'1\')\n if bits != 1 and math.factorial(bits - 1) % bits == bits - 1:\n res += 1\n return res \n```\n```Java []\nclass Solution {\n public int countPrimeSetBits(int left, int right) {\n int[] primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 };\n boolean[] prime_bool = new boolean[32];\n for (int p : primes)\n prime_bool[p] = true;\n int cnt = 0;\n for (int i = left; i <= right; i++) {\n int bCount = Integer.bitCount(i);\n if (prime_bool[bCount])\n cnt++;\n }\n\n return cnt;\n }\n}\n```\n```C []\nint countON(int n) {\n int iCnt = 0;\n while (n) {\n n = n & (n - 1);\n iCnt++;\n }\n return iCnt;\n}\nbool isPrime(int iNo) {\n bool bFlag = true;\n if (iNo <= 1) {\n return false;\n }\n int i = 0;\n for (i = 2; i <= (iNo / 2); i++) {\n if (iNo % i == 0) {\n bFlag = false;\n break;\n }\n }\n return bFlag;\n}\nint countPrimeSetBits(int left, int right) {\n bool bRet = false;\n int iCnt = 0, iNum = 0;\n while (left <= right) {\n iNum = countON(left);\n\n if (isPrime(iNum) == true) {\n iCnt++;\n }\n left++;\n }\n return iCnt;\n}\n```\n```Java []\nclass Solution {\n public int countPrimeSetBits(int l, int r) {\n Set<Integer> primes = new HashSet<>(Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29));\n int cnt = 0;\n for (int i = l; i <= r; i++) {\n int bits = 0;\n for (int n = i; n > 0; n >>= 1)\n bits += n & 1;\n cnt += primes.contains(bits) ? 1 : 0;\n }\n return cnt;\n }\n}\n```\n```python []\nclass Solution(object):\n def countPrimeSetBits(self, L, R):\n """\n :type L: int\n :type R: int\n :rtype: int\n """\n res = 0\n for i in range(L, R+1):\n bits = bin(i).count(\'1\')\n if bits != 1 and math.factorial(bits - 1) % bits == bits - 1:\n res += 1\n return res \n```\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```\nclass Solution {\nprivate:\n bool isPrime(int n) {\n if (n == 1)\n return false;\n for (int i = 2; i <= n / 2; i++)\n if (n % i == 0)\n return false;\n return true;\n }\n\npublic:\n int countPrimeSetBits(int left, int right) {\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n int cnt = 0;\n for (int i = left; i <= right; i++) {\n int bits = __builtin_popcount(i);\n if (isPrime(bits))\n cnt++;\n }\n return cnt;\n }\n};\n```\n\n | 2 | 0 | ['C', 'Python', 'C++', 'Java', 'Python3'] | 1 |
prime-number-of-set-bits-in-binary-representation | ++ Intuitive Solution || Well-Explained ✌️🔥 | intuitive-solution-well-explained-by-jas-spn8 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves counting the number of integers in a given range whose binary repr | jasneet_aroraaa | NORMAL | 2024-02-11T15:41:57.036390+00:00 | 2024-02-11T15:41:57.036416+00:00 | 113 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves counting the number of integers in a given range whose binary representation contains a prime number of set bits. We need to devise a method to efficiently count such numbers within the given range.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Define a helper function to count the number of set bits in a given integer.\n2. Iterate through each integer in the given range.\n3. For each integer, count the set bits using the helper function.\n4. Check if the count of set bits is a prime number.\n5. If it\'s a prime number, increment the counter.\n6. Return the final count as the result.\n\n# Complexity\n* Time complexity:\n * The time complexity of counting set bits in a number is O(log n), where n is the number of bits in the integer.\n * For each integer in the given range, we perform the set bit counting operation. So, overall, the time complexity is O((right - left) * log(right)).\n\n- Space complexity:\n The space complexity is O(1) as we are using only a constant amount of extra space.\n\n# Code\n```\nclass Solution {\npublic:\n int helper(int n) {\n // count set bits\n int setBits = 0;\n while (n) {\n setBits += n % 2;\n n /= 2;\n }\n\n // check prime\n if (setBits == 1) return 0;\n for (int i = 2; i < setBits; i++) {\n if (setBits % i == 0) return 0;\n }\n return 1;\n }\n\n int countPrimeSetBits(int left, int right) {\n int ans = 0;\n for (int i = left; i <= right; i++) {\n ans += helper(i);\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Math', 'Bit Manipulation', 'C++'] | 0 |
prime-number-of-set-bits-in-binary-representation | C++ || Explained || Short code using sets | c-explained-short-code-using-sets-by-adi-lska | \n# Approach\n Describe your approach to solving the problem. \nTo represent numbers upto 10^6 in binary you only need 20 bits hence the maximum number of 1 bit | adityakhare863 | NORMAL | 2023-07-26T07:07:26.883328+00:00 | 2023-07-26T07:07:26.883358+00:00 | 25 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo represent numbers upto 10^6 in binary you only need 20 bits hence the maximum number of 1 bits in binary representation of numbers from left to right is 20. Hence we store prime numbers upto 20 in $$store$$. \n\nAfter which we count number of set bits in every number from left to right using : $$ n= n & (n-1)$$.\n\nIf you observe whenever we subtract 1 from a number $$n$$ the rightmost set bit of that number becomes unset and every bit after that become 1. The & of which leaves us with total number of set bits of n - 1. \n\nTry understanding it with an example: \n7 in binary: 111\n6 (7-1) in binary : 110\n7&6: 110\n\nAnother example: \n78 in binary: 1001110\n77 (78 - 1) in binary: 1001101\n78 & 77: 1001100\n\nHence, we clearly see whenever we $$n&(n-1)$$ we are left with one setbit less than in n.\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n std::set<int> store {2,3,5,7,11,13,17,19};\n int count {}; int temp {}; int c {};\n for(int i= left; i<=right; i++){\n temp = i;\n c = 0;\n while(temp){\n c++;\n temp = temp & temp-1;\n }\n if(store.count(c))count++;\n }\n return count;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
prime-number-of-set-bits-in-binary-representation | Python one-liner | python-one-liner-by-trpaslik-li0l | Intuition\nJust iterate and sum\n\nNote that 10**6 has 20 bits, so we need only primes <= 20.\nAlso, python 3.10 introduced int.bit_count() that is more or less | trpaslik | NORMAL | 2023-05-12T13:02:11.115699+00:00 | 2023-05-12T13:02:11.115740+00:00 | 779 | false | # Intuition\nJust iterate and sum\n\nNote that 10**6 has 20 bits, so we need only primes <= 20.\nAlso, python 3.10 introduced int.bit_count() that is more or less equivalent to bin(x).count("1") but obviously much faster.\n\n\n# Complexity\n- Time complexity: O(n) - iterating over the left..right range.\n\n- Space complexity: O(1) - sum is computed via generator\n\n# Code\n```\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n return (primes := (2,3,5,7,11,13,17,19)) and sum((x.bit_count() in primes) for x in range(left, right+1))\n \n``` | 2 | 0 | ['Python3'] | 0 |
prime-number-of-set-bits-in-binary-representation | Solution | solution-by-deleted_user-5w4c | C++ []\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int ans=0;\n while(left<=right) {\n int cnt=__bui | deleted_user | NORMAL | 2023-04-26T21:37:47.182245+00:00 | 2023-04-26T22:02:30.426431+00:00 | 1,296 | false | ```C++ []\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int ans=0;\n while(left<=right) {\n int cnt=__builtin_popcount(left);\n if(cnt==2 || cnt==3 || cnt==5 || cnt==7 || cnt==11 || cnt==13 || cnt==17 || cnt==19)\n ++ans;\n ++left;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n c = 0\n\n for i in range(left, right + 1):\n if i.bit_count() in primes:\n c += 1\n \n return c\n```\n\n```Java []\nclass Solution {\n private final int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17, 19};\n private int cnk(int n, int k) {\n if (n <= 0 || k <= 0) {\n return 0;\n }\n long f1 = 1;\n for (int i = k + 1; i <= n; i++) {\n f1 *= i;\n }\n long f2 = 1;\n for (int i = 2; i <= n - k; i++) {\n f2 *= i;\n }\n return (int) (f1 / f2);\n }\n private int primeBitNumbersCount(int length, int minus) {\n int result = 0;\n for (int i = 0; i < primes.length && primes[i] - minus <= length; i++) {\n result += cnk(length, primes[i] - minus);\n }\n return result;\n }\n private int primesTo(int number) {\n for (int i = primes.length - 1; i >= 0; i--) {\n if (number >= primes[i]) {\n return i + 1;\n }\n }\n return 0;\n }\n private int primeBitNumbersCount(int number) {\n int pointer = 0x40000000;\n int position = 31;\n int bitsSet = 0;\n int primeBitNumbersCount = 0; \n\n while (pointer != 0) {\n if ((number & pointer) > 0) {\n primeBitNumbersCount += primeBitNumbersCount(position - 1, bitsSet);\n bitsSet++;\n }\n pointer >>>= 1;\n position--;\n }\n primeBitNumbersCount += primesTo(bitsSet);\n return primeBitNumbersCount;\n }\n public int countPrimeSetBits(int left, int right) {\n return primeBitNumbersCount(right) - primeBitNumbersCount(left - 1);\n }\n}\n```\n | 2 | 0 | ['C++', 'Java', 'Python3'] | 0 |
prime-number-of-set-bits-in-binary-representation | Simple Brute Force Approach Java | simple-brute-force-approach-java-by-vand-14d3 | \nclass Solution {\n private boolean isPrime(int num){\n if(num==1 || num==0)return false;\n for(int i=2;i*i<=num;i++){\n if(num%i== | vandittalwadia | NORMAL | 2023-04-14T06:56:58.510516+00:00 | 2023-04-14T06:56:58.510557+00:00 | 185 | false | ```\nclass Solution {\n private boolean isPrime(int num){\n if(num==1 || num==0)return false;\n for(int i=2;i*i<=num;i++){\n if(num%i==0)return false;\n }\n return true;\n }\n public int countPrimeSetBits(int left, int right) {\n int ans=0;\n for(int i=left;i<=right;i++){\n int num = i;\n int count=0;\n while(num>0){\n int bit = num%2;\n if(bit==1){\n count++;\n }\n num=num/2;\n }\n if(isPrime(count))ans++;\n }\n return ans;\n }\n}\n``` | 2 | 0 | ['Bit Manipulation', 'Java'] | 1 |
prime-number-of-set-bits-in-binary-representation | simple cpp solution | simple-cpp-solution-by-prithviraj26-rksw | 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 | prithviraj26 | NORMAL | 2023-02-27T06:02:19.111901+00:00 | 2023-02-27T06:02:19.111946+00:00 | 1,215 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int solve(int a)\n {\n int ans=0;\n while(a>0)\n {\n if(a%2==1)ans++;\n\n a/=2;\n }\n return ans;\n }\n bool isprime(int a)\n {\n if(a==1)return false;\n for(int i=2;i<=sqrt(a);i++)\n {\n if(a%i==0)return false;\n }\n return true;\n }\n int countPrimeSetBits(int left, int right) {\n int ans=0;\n for(int i=left;i<=right;i++)\n {\n int a=solve(i);\n if(isprime(a)==true)\n {\n ans++;\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Math', 'Bit Manipulation', 'C++'] | 0 |
prime-number-of-set-bits-in-binary-representation | CPP SOLUTION || EASY TO UNDERSTAND || SIMPLE AND EASY CODE | cpp-solution-easy-to-understand-simple-a-5jax | 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 | Abhishek777888 | NORMAL | 2023-01-01T12:45:03.954144+00:00 | 2023-01-01T12:45:03.954214+00:00 | 1,346 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nbool prime (int x)\n{\n bool flag = false ;\n if(x==1) return false;\n for(int i =2 ; i < x ; i++)\n {\n if(x % i ==0 ){flag=true;break;}\n }\n if(flag)return false;\n return true;\n}\n string convert(int x)\n {\n string ans="";\n while( x > 0)\n {\n if(x % 2 == 0){ans+="0";}\n else {ans+=\'1\';}\n x/=2;\n }\n return ans;\n }\n int countone(string s)\n {\n int count=0;\n for(int i= 0 ;i < s.size();i++)\n {\n if(s[i] == \'1\'){count++;}\n }\n return count;\n }\n int countPrimeSetBits(int left, int right) {\n int ans=0;\n for(int i = left ;i <= right ;i++)\n {\n int x = countone(convert(i));\n\n if(prime(x)==true){ans++;}\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Bit Manipulation', 'C++'] | 0 |
prime-number-of-set-bits-in-binary-representation | 70% BEATS || C++ || SIMPLE || EASY | 70-beats-c-simple-easy-by-abhay_12345-fhh9 | \nclass Solution {\npublic:\n int countPrimeSetBits(int &left, int &right) {\n vector<int> v = {0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0, | abhay_12345 | NORMAL | 2022-09-08T06:50:24.555296+00:00 | 2022-09-08T06:50:24.555334+00:00 | 549 | false | ```\nclass Solution {\npublic:\n int countPrimeSetBits(int &left, int &right) {\n vector<int> v = {0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0};\n int ans = 0,x,k;\n while(left <= right){\n x = 0;\n k = left;\n while(k){\n x += (k&1);\n k = k >> 1;\n }\n ans += v[x];\n left++;\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Bit Manipulation', 'C', 'C++'] | 1 |
prime-number-of-set-bits-in-binary-representation | Easiest Java ✅|| short and simple✅|| straight forward Solution✅ | easiest-java-short-and-simple-straight-f-vlsd | \n\nclass Solution {\n public int calculateSetBits(String s){\n int count=0;\n for (int i = 0; i < s.length(); i++) {\n if(s.charA | vaibhavnirmal2001 | NORMAL | 2022-08-07T08:08:03.420529+00:00 | 2022-08-07T08:08:03.420570+00:00 | 617 | false | \n```\nclass Solution {\n public int calculateSetBits(String s){\n int count=0;\n for (int i = 0; i < s.length(); i++) {\n if(s.charAt(i)==\'1\') count++;\n }\n return count;\n }\n\n public boolean isPrime(int n){\n if (n==0 || n==1) return false;\n for (int i = 2; i <= n/2; i++) {\n if(n%i ==0 ) return false;\n }\n// System.out.println(n+" - ");\n return true;\n }\n\n public int countPrimeSetBits(int left, int right) {\n int count=0;\n for(int i=left;i<=right;i++){\n String b= Integer.toBinaryString(i);\n\n int n=calculateSetBits(b);\n\n if(isPrime(n)) count++;\n }\n return count;\n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
prime-number-of-set-bits-in-binary-representation | [JAVA] | 3 Methods | Maths Explained | Bruteforce | Better | Optimal | java-3-methods-maths-explained-bruteforc-9goi | \n//Bruteforce Approach\n\nclass Solution {\n public int countPrimeSetBits(int left, int right) {\n int cnt=0;\n for(int i=left;i<=right;i++)\n | anand-swaroop-pandey | NORMAL | 2022-05-29T22:45:33.435722+00:00 | 2022-05-29T22:45:33.435750+00:00 | 399 | false | ```\n//Bruteforce Approach\n\nclass Solution {\n public int countPrimeSetBits(int left, int right) {\n int cnt=0;\n for(int i=left;i<=right;i++)\n if(primeSetBits(i))\n cnt++;\n return cnt;\n }\n \n public static boolean primeSetBits(int num)\n {\n int cntSetBits=countSetBits(num);\n return isPrime(cntSetBits);\n }\n \n public static int countSetBits(int num)//Kernighan\'s Algorithm\n {\n int count=0;\n while(num!=0)\n {\n int rmsbm=rMSBM(num);\n num=num-rmsbm;\n count++; \n }\n return count;\n }\n\t\n public static int rMSBM(int num)\n {\n\t int rmsbm=num & twosCompliment(num);\n\t return rmsbm;\n }\n\t\n public static int twosCompliment(int num)\n {\n return -num;//return (~num+1);\n }\n \n public static boolean isPrime(int num)\n {\n if(num<=1)\n\t return false;\n \n for(int i=2;(i*i)<=num;i++)\n if((num%i)==0)\n return false; \n\t \n return true; \n }\n}\n```\n\n```\n//Better Approach\nclass Solution {\n public int countPrimeSetBits(int left, int right) {\n int cnt=0;\n for(int i=left;i<=right;i++)\n if(isPrime(Integer.bitCount(i)))\n cnt++;\n return cnt;\n }\n \n public static boolean isPrime(int num)\n {\n if(num<=1)\n\t return false;\n \n for(int i=2;(i*i)<=num;i++)\n if((num%i)==0)\n return false; \n\t \n return true; \n }\n}\n```\n\n```\n//Optimal Approach\n/*\nAn Integer is Represented using 32 bits so total bits =32 out of these 32 bits some will be Set/On while Other will be Unset/Off \nso all we need to Do is Pre Compute all the prime Numbers in the the Range [1,32](both Inclusive)\nAs no.of primes are limited we can use Hashset to check no.of set bits is prime or not.\n*/\n\nclass Solution {\n public int countPrimeSetBits(int left, int right) {\n HashSet<Integer>prime=new HashSet<>();\n prime.add(2);\n prime.add(3);\n prime.add(5);\n prime.add(7);\n prime.add(11);\n prime.add(13);\n prime.add(17);\n prime.add(19);\n\t prime.add(23);\n prime.add(29);\n prime.add(31);\n \n int cnt=0;\n for(int i=left;i<=right;i++)\n if(prime.contains(Integer.bitCount(i)))\n cnt++;\n \n return cnt; \n }\n}\n\n``` | 2 | 0 | ['Java'] | 1 |
prime-number-of-set-bits-in-binary-representation | o(1) to check Prime or not | o1-to-check-prime-or-not-by-tarunsriniva-uon3 | As no.of primes are limited we can use Hashset to check no.of set bits is prime or not\n\nclass Solution {\n public int countPrimeSetBits(int left, int right | tarunsrinivas | NORMAL | 2022-04-22T06:15:23.857794+00:00 | 2022-04-22T06:15:23.857837+00:00 | 1,581 | false | As no.of primes are limited we can use Hashset to check no.of set bits is prime or not\n```\nclass Solution {\n public int countPrimeSetBits(int left, int right) {\n HashSet<Integer> s=new HashSet<>();\n s.add(2);\n s.add(3);\n s.add(5);\n s.add(7);\n s.add(11);\n s.add(13);\n s.add(17);\n s.add(19);\n s.add(23);\n s.add(29);\n s.add(31);\n int res=0;\n for(int i=left;i<=right;i++){\n int x=num(i);\n if(s.contains(x))\n res++;\n }\n return res;\n }\n public int num(int x){\n int res=0;\n for(int i=0;i<32;i++){\n if((x&(1<<i))!=0)\n res++;\n }\n return res;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
prime-number-of-set-bits-in-binary-representation | Easy solution || Faster than others || bit manipulation | easy-solution-faster-than-others-bit-man-66ab | ```\nclass Solution {\npublic:\n bool isPrime(int n){\n if(n==2||n==3||n==5 ||n==7||n==11||n==13||n==17||n==19)\n return true;\n ret | Shristha | NORMAL | 2022-03-31T13:48:24.596032+00:00 | 2022-03-31T13:48:24.596083+00:00 | 378 | false | ```\nclass Solution {\npublic:\n bool isPrime(int n){\n if(n==2||n==3||n==5 ||n==7||n==11||n==13||n==17||n==19)\n return true;\n return false;\n }\n int setCount(int n){\n int count=0;\n while(n>0){\n n=n&(n-1);\n count++;\n }\n return count;\n }\n int countPrimeSetBits(int left, int right) {\n int res=0;\n for(int i=left;i<=right;i++){\n int count=setCount(i);\n if(isPrime(count))\n res++;\n \n }\n return res;\n }\n}; | 2 | 0 | ['Bit Manipulation', 'C', 'C++'] | 0 |
prime-number-of-set-bits-in-binary-representation | Prime Number of Set Bits in Binary Representation Solution Java | prime-number-of-set-bits-in-binary-repre-r2tr | class Solution {\n public int countPrimeSetBits(int L, int R) {\n // { 2, 3, 5, 7, 11, 13, 17, 19 }th bits are 1s\n // (10100010100010101100)2 = (665772) | bhupendra786 | NORMAL | 2022-03-24T07:35:42.672823+00:00 | 2022-03-24T07:35:42.672855+00:00 | 111 | false | class Solution {\n public int countPrimeSetBits(int L, int R) {\n // { 2, 3, 5, 7, 11, 13, 17, 19 }th bits are 1s\n // (10100010100010101100)2 = (665772)10\n final int magic = 665772;\n int ans = 0;\n\n for (int n = L; n <= R; ++n)\n if ((magic & 1 << Integer.bitCount(n)) > 0)\n ++ans;\n\n return ans;\n }\n}\n | 2 | 0 | ['Math', 'Bit Manipulation'] | 0 |
prime-number-of-set-bits-in-binary-representation | c++ faster than 95.75% | c-faster-than-9575-by-bholanathbarik9748-ml1z | \nclass Solution\n{\npublic:\n bool prime(int x)\n {\n return (x == 2 || x == 3 || x == 5 || x == 7 ||\n x == 11 || x == 13 || x == | bholanathbarik9748 | NORMAL | 2021-11-02T15:35:31.672711+00:00 | 2021-11-02T15:35:31.672742+00:00 | 94 | false | ```\nclass Solution\n{\npublic:\n bool prime(int x)\n {\n return (x == 2 || x == 3 || x == 5 || x == 7 ||\n x == 11 || x == 13 || x == 17 || x == 19);\n }\n\n int countPrimeSetBits(int left, int right)\n {\n int count = 0;\n int n;\n for (int i = left; i <= right; i++)\n {\n if (prime(__builtin_popcount(i)))\n count++;\n }\n\n return count;\n }\n};\n``` | 2 | 0 | [] | 0 |
prime-number-of-set-bits-in-binary-representation | C++ Easy bit manipulation Solution | c-easy-bit-manipulation-solution-by-saat-2qk7 | \nclass Solution {\npublic:\n int CheckCnt(int n) {\n int cnt = 0;\n \n while (n) {\n cnt++;\n n = n & (n - 1);\n | 20250122.saathvik93 | NORMAL | 2021-10-14T02:27:43.165671+00:00 | 2021-10-14T02:27:43.165713+00:00 | 122 | false | ```\nclass Solution {\npublic:\n int CheckCnt(int n) {\n int cnt = 0;\n \n while (n) {\n cnt++;\n n = n & (n - 1);\n }\n \n return cnt;\n }\n \n bool isPrime(int n) {\n if (n <= 1) return false;\n\n for (int i = 2; i < n; ++i)\n if (n % i == 0)\n return false;\n\n return true;\n }\n \n int countPrimeSetBits(int left, int right) {\n int b_cnt;\n int fin_cnt;\n \n for (int i = left; i <= right; i++) {\n b_cnt = CheckCnt(i);\n if (isPrime(b_cnt))\n fin_cnt++;\n }\n \n return fin_cnt;\n }\n};\n``` | 2 | 0 | [] | 0 |
prime-number-of-set-bits-in-binary-representation | Java Brute Force. (Count Set Bits + Prime Checking) | java-brute-force-count-set-bits-prime-ch-7ecd | \nclass Solution {\n public int countPrimeSetBits(int left, int right) {\n int primes = 0;\n for (int i = left; i <= right; i++) {\n | abhishek_1110 | NORMAL | 2021-10-10T05:14:49.974362+00:00 | 2021-10-10T05:14:49.974410+00:00 | 173 | false | ```\nclass Solution {\n public int countPrimeSetBits(int left, int right) {\n int primes = 0;\n for (int i = left; i <= right; i++) {\n //counting set bits\n int x = countSetBits(i);\n if (checkingPrime(x)) {\n primes++;\n }\n }\n return primes;\n }\n \n public int countSetBits(int n) {\n int count = 0;\n while (n != 0) {\n count++;\n n = n & (n - 1);\n }\n return count;\n }\n \n public boolean checkingPrime(int n) {\n if (n <= 1)\n return false;\n \n // Check if number is 2\n else if (n == 2)\n return true;\n \n // Check if n is a multiple of 2\n else if (n % 2 == 0)\n return false;\n \n // If not, then just check the odds\n for (int i = 3; i <= Math.sqrt(n); i += 2)\n {\n if (n % i == 0)\n return false;\n }\n return true;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
prime-number-of-set-bits-in-binary-representation | Python - solution for only one line, | python-solution-for-only-one-line-by-ste-ka54 | constraints: 1 <= left <= right <= 10^6\n10^6 = \'0b11110100001001000000\'\nmaximum number of 1\'s present is 20\nprime numbers within 20 is all of [2, 3, 5, 7, | steven5601 | NORMAL | 2021-08-11T09:17:20.956264+00:00 | 2021-08-11T09:17:55.657651+00:00 | 129 | false | constraints: 1 <= left <= right <= 10^6\n10^6 = \'0b11110100001001000000\'\nmaximum number of 1\'s present is 20\nprime numbers within 20 is all of [2, 3, 5, 7, 11, 13, 17, 19]\n```\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n return len([(list(bin(i)).count(\'1\')) for i in range(left, right+1) if (list(bin(i)).count(\'1\')) in [2, 3, 5, 7, 11, 13, 17, 19]])\n``` | 2 | 0 | [] | 1 |
prime-number-of-set-bits-in-binary-representation | Runtime:-4ms faster than 95% C++ solution | runtime-4ms-faster-than-95-c-solution-by-al5q | ```\nint ones(int num){\nint res=0;\nwhile(n>0){\nnum = num & (num-1);\nres++;\n}\nreturn res;\n}\n int countPrimeSetBits(int left, int right) {\n int | vdas53073 | NORMAL | 2021-07-28T04:12:28.949193+00:00 | 2021-07-28T11:14:47.768080+00:00 | 218 | false | ```\nint ones(int num){\nint res=0;\nwhile(n>0){\nnum = num & (num-1);\nres++;\n}\nreturn res;\n}\n int countPrimeSetBits(int left, int right) {\n int res=0;\n for(int i=left;i<=right;i++){\n int ans = ones(i);\n if((ans & 1)!=0 || ans==2){\n if(ans==3)\n res++;\n if(ans!=1 && ans%3!=0)\n res++;\n }\n }\n return res;\n } | 2 | 0 | ['Bit Manipulation', 'C', 'C++'] | 1 |
prime-number-of-set-bits-in-binary-representation | Java Naive Approach | java-naive-approach-by-dryash213-9jdr | \tpublic int CountNumberofSetBit(int n){\n\t// -n ==2\'s Complement\n\t\t\tint counter=0;\n\t\t\twhile (n!=0){\n\t\t\t\tint temp = n & -n;\n\t\t\t\tn-=temp | dryash213 | NORMAL | 2021-06-19T05:32:19.884400+00:00 | 2021-06-19T05:32:19.884433+00:00 | 80 | false | \tpublic int CountNumberofSetBit(int n){\n\t// -n ==2\'s Complement\n\t\t\tint counter=0;\n\t\t\twhile (n!=0){\n\t\t\t\tint temp = n & -n;\n\t\t\t\tn-=temp;\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t\treturn(counter);\n\t\t}\n\t\tpublic int countPrimeSetBits(int left, int right) {\n\t\t\tint ans=0;\n\t\t\tfor(int i =left;i<=right;i++){\n\t\t\t\tint count=CountNumberofSetBit(i);\n\t\t\t\tint div=0;\n\t\t\t\tfor(int j=2;j<count;j++){\n\t\t\t\t\tif(count%j==0){\n\t\t\t\t\t\tdiv++;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(!(div>0||count<=1)){\n\t\t\t\t\tans++;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ans;\n\t\t} | 2 | 0 | [] | 0 |
prime-number-of-set-bits-in-binary-representation | Python | Sieve of Eratosthenes | python-sieve-of-eratosthenes-by-sanjaych-fckp | \ndef get_prime_list(n: int) -> list:\n # Sieve of Eratosthenes\n primes = [True]*(n+1)\n primes[0] = primes[1] = False\n\n i = 2\n n = 32\n w | sanjaychandak95 | NORMAL | 2021-05-23T11:42:17.397967+00:00 | 2021-05-23T11:42:17.398009+00:00 | 133 | false | ```\ndef get_prime_list(n: int) -> list:\n # Sieve of Eratosthenes\n primes = [True]*(n+1)\n primes[0] = primes[1] = False\n\n i = 2\n n = 32\n while i*i < n:\n if primes[i]:\n j = i\n while i*j < n:\n primes[i*j] = False\n j += 1\n i+=1\n return primes\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n # first find prime between 1 to 32 ( 32 bit integer)\n is_prime = get_prime_list(32)\n return len(list(filter(lambda x: is_prime[bin(x).count(\'1\')], range(left,right+1))))\n``` | 2 | 0 | ['Python', 'Python3'] | 0 |
prime-number-of-set-bits-in-binary-representation | Faster than 99.16 java soultion | faster-than-9916-java-soultion-by-rachit-ibdu | class Solution {\n public boolean prime(int n)\n {\n if(n==2 || n==3|| n==5|| n==7|| n==11||n==13|| n==17|| n==19 || n==23)\n {\n | Rachit_3850 | NORMAL | 2021-05-12T09:04:32.433792+00:00 | 2021-05-12T09:04:32.433824+00:00 | 406 | false | class Solution {\n public boolean prime(int n)\n {\n if(n==2 || n==3|| n==5|| n==7|| n==11||n==13|| n==17|| n==19 || n==23)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n public int countPrimeSetBits(int left, int right) {\n if(right<15)\n return right-left;\n int count=0;\n for(int i=left;i<=right;i++)\n {\n int n= Integer.bitCount(i);\n if(prime(n))\n count++;\n }\n return count;\n \n }\n} | 2 | 0 | ['Bit Manipulation', 'Java'] | 0 |
prime-number-of-set-bits-in-binary-representation | Faster than 94.62% of Python3 online submissions | faster-than-9462-of-python3-online-submi-xd8g | \nclass Solution:\n def countPrimeSetBits(self, L: int, R: int) -> int:\n prime = {2,3,5,7,11,13,17,19}\n count = 0\n for i in range(L,R | bhardwajsiddhant03 | NORMAL | 2021-02-16T00:19:05.111596+00:00 | 2021-02-16T00:19:05.111642+00:00 | 59 | false | ```\nclass Solution:\n def countPrimeSetBits(self, L: int, R: int) -> int:\n prime = {2,3,5,7,11,13,17,19}\n count = 0\n for i in range(L,R + 1):\n num = bin(i).count(\'1\')\n if num in prime:\n count += 1\n return count\n``` | 2 | 0 | [] | 0 |
prime-number-of-set-bits-in-binary-representation | [JAVA] Clean Code, O(N log N) Optimal Solution | java-clean-code-on-log-n-optimal-solutio-ofwe | \nclass Solution {\n \n private boolean isPrime (int n) {\n return n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 || n== 17 || n == 19; | anii_agrawal | NORMAL | 2020-07-14T13:27:01.446688+00:00 | 2020-07-14T13:27:01.446777+00:00 | 139 | false | ```\nclass Solution {\n \n private boolean isPrime (int n) {\n return n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 || n== 17 || n == 19;\n }\n \n public int countPrimeSetBits(int L, int R) {\n \n int ans = 0;\n \n while (L <= R) {\n if (isPrime (Integer.bitCount (L++))) {\n ++ans;\n }\n }\n \n return ans;\n }\n}\n```\n\nPlease help to **UPVOTE** if this post is useful for you.\nIf you have any questions, feel free to comment below.\n**HAPPY CODING :)\nLOVE CODING :)**\n | 2 | 0 | [] | 1 |
prime-number-of-set-bits-in-binary-representation | [C++] Easy Solution to understand (No Built-in Methods) | c-easy-solution-to-understand-no-built-i-xymy | \n\nPlease upvote if you like this post.\n\n\nResult: Accepted\n\nclass Solution {\npublic:\n bool isPrime(int n){\n if(n==1)\n return fals | pulkitswami7 | NORMAL | 2020-05-31T11:53:38.161385+00:00 | 2020-06-03T07:14:39.730210+00:00 | 159 | false | <hr>\n\n**Please upvote if you like this post.**\n<hr>\n\n**Result:** Accepted\n```\nclass Solution {\npublic:\n bool isPrime(int n){\n if(n==1)\n return false;\n int count=0;\n for(int i=2;i<=n;i++){\n if(n%i==0)\n count++;\n }\n if(count==1)\n return true;\n return false;\n }\n \n int countPrimeSetBits(int L, int R) {\n int noPrime = 0;\n for(int i=L;i<=R;i++){\n int num=i,countOne=0;\n while(num>0){\n if(num%2==1)\n countOne++;\n num=num/2;\n }\n if(isPrime(countOne))\n noPrime++;\n }\n return noPrime;\n }\n};\n``` | 2 | 0 | [] | 1 |
prime-number-of-set-bits-in-binary-representation | Solution in Python 3 (beats ~98%) (one line) | solution-in-python-3-beats-98-one-line-b-6nap | ```\nclass Solution:\n def countPrimeSetBits(self, L: int, R: int) -> int:\n \treturn sum(1 for i in range(L,R+1) if bin(i).count(\'1\') in {2,3,5,7,11,13 | junaidmansuri | NORMAL | 2019-09-13T06:12:52.693627+00:00 | 2019-09-13T06:18:27.011965+00:00 | 374 | false | ```\nclass Solution:\n def countPrimeSetBits(self, L: int, R: int) -> int:\n \treturn sum(1 for i in range(L,R+1) if bin(i).count(\'1\') in {2,3,5,7,11,13,17,19})\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com | 2 | 1 | ['Python', 'Python3'] | 0 |
prime-number-of-set-bits-in-binary-representation | Java with Sieve of Eratosphenus | java-with-sieve-of-eratosphenus-by-space-cd3q | \nclass Solution {\n boolean[] prime;\n void sieveOfEratosphenus(int n){\n prime = new boolean[n+1];\n for(int i = 0; i < n; i++)\n | space_cat | NORMAL | 2018-08-30T18:15:51.237435+00:00 | 2018-08-30T18:15:51.237482+00:00 | 225 | false | ```\nclass Solution {\n boolean[] prime;\n void sieveOfEratosphenus(int n){\n prime = new boolean[n+1];\n for(int i = 0; i < n; i++)\n prime[i] = true;\n \n for(int p = 2; p*p <=n; p++)\n {\n // If prime[p] is not changed, then it is a prime\n if(prime[p] == true)\n {\n // Update all multiples of p\n for(int i = p*2; i <= n; i += p)\n prime[i] = false;\n }\n }\n prime[1] = false;\n }\n public int numberOfOnes(int n){\n String inBinary = Integer.toBinaryString(n);\n int res = 0;\n for(int i = 0; i < inBinary.length(); i++){\n if(inBinary.charAt(i)==\'1\'){\n res++;\n }\n }\n return res;\n }\n \n public int countPrimeSetBits(int L, int R) {\n int sum = 0;\n sieveOfEratosphenus(R);\n System.out.print(prime[1]);\n for(int i = L; i<=R; i++){\n int ones = numberOfOnes(i);\n if(prime[ones] == true) sum++;\n }\n return sum;\n }\n}\n``` | 2 | 0 | [] | 0 |
prime-number-of-set-bits-in-binary-representation | 5 lines Python Solution and Simple Explanation | 5-lines-python-solution-and-simple-expla-3owo | \nclass Solution(object):\n def countPrimeSetBits(self, L, R):\n \n # "L, R in the range [1, 10^6]" means it is less than 2**20.\n # So, | positive235 | NORMAL | 2018-04-10T22:40:06.782019+00:00 | 2018-04-10T22:40:06.782019+00:00 | 246 | false | ```\nclass Solution(object):\n def countPrimeSetBits(self, L, R):\n \n # "L, R in the range [1, 10^6]" means it is less than 2**20.\n # So, possible prime numbers are 2, 3, 5, 7, 11, 13, 17, 19.\n \n k = 0\n for n in range(L , R + 1):\n if bin(n).count(\'1\') in [2,3,5,7,11,13,17,19]:\n k = k + 1 \n return k \n \n``` | 2 | 0 | [] | 1 |
prime-number-of-set-bits-in-binary-representation | O(1) time c++ solution | o1-time-c-solution-by-yoyo0720-cgxo | The idea is based on the following observation:\nIf we want to find out how many numbers in the range of [1,52] have prime number of set bits, we first examine | yoyo0720 | NORMAL | 2018-03-18T16:33:56.818234+00:00 | 2018-03-18T16:33:56.818234+00:00 | 384 | false | The idea is based on the following observation:\nIf we want to find out how many numbers in the range of [1,52] have prime number of set bits, we first examine the most significant bit of the binary representation 110100.\nFor numbers less than 100000, i.e. in the range of [0,11111], we can fill the 5 bits with 2 or 3 or 5 ones, so the count in this range is C(5,2)+C(5,3)+C(5,5)=21.\nWe then move to the next 1 and count the numbers in the range [100000,101111], we can fill the 4 bits with 1 or 2 or 4 ones (plus the 1 in the beginning that makes the total number of ones 2 or 3 or 5), so the count is C(4,1)+C(4,2)+C(4,4)=11.\nWe then move to the next \'1\' and add C(2,0)+C(2,1)=3 to the total count.\nDon\'t forget to add one more for 110100 it self. So the final answer is 21+11+3+1=36.\nFor the count in range of [L,R], we do the calculation for R and L-1 and the result is the difference.\nI know for the given input range this code is more complicated but runs slower than some linear time implementation (97.77%), I still want to share this theoretically better solution:)\n```\nclass Solution {\npublic:\n int countPrimeSetBits(int L, int R) {\n return countPrimeSetBitsNumber(R)-countPrimeSetBitsNumber(L-1);\n }\n int countPrimeSetBitsNumber(int num)\n {\n unordered_set<int> prime={2,3,5,7,11,13,17,19};\n int numBitsRight = log2(num), base = 1 << numBitsRight, numOnesLeft = 0, ans = 0;\n while(base > 0)\n {\n if (num & base)\n {\n int nChoosek = 1;\n for (int i = 0; i <= numBitsRight; i++)\n {\n if (prime.count(i + numOnesLeft))\n ans += nChoosek;\n nChoosek = nChoosek * (numBitsRight - i) / (i + 1);\n }\n numOnesLeft++;\n }\n base = base >> 1;\n numBitsRight--;\n }\n return ans+prime.count(numOnesLeft);\n }\n};\n``` | 2 | 0 | [] | 2 |
prime-number-of-set-bits-in-binary-representation | Java 2 lines | java-2-lines-by-climberig-frzf | ```\n public int countPrimeSetBits(int L, int R) {\n Set primes = new HashSet<>(Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19));\n return (int)IntStrea | climberig | NORMAL | 2018-03-09T21:34:07.717036+00:00 | 2018-03-09T21:34:07.717036+00:00 | 230 | false | ```\n public int countPrimeSetBits(int L, int R) {\n Set<Integer> primes = new HashSet<>(Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19));\n return (int)IntStream.range(L, R + 1).map(Integer::bitCount).filter(primes::contains).count();\n } | 2 | 0 | [] | 0 |
prime-number-of-set-bits-in-binary-representation | Counting Ones | counting-ones-by-khaled-alomari-cp7m | Complexity
Time complexity:
O((R−L)∗log(R−L))
Space complexity:
O(1)
Code | khaled-alomari | NORMAL | 2025-02-24T18:39:07.467761+00:00 | 2025-02-24T18:39:07.467761+00:00 | 58 | false | # Complexity
- Time complexity:
$$O((R - L) * log(R - L))$$
- Space complexity:
$$O(1)$$
# Code
```typescript []
function countPrimeSetBits(left: number, right: number) {
const countOnes = (num: number) => {
let count = 0;
for (const b of num.toString(2)) count += +(b === '1');
return count;
};
const primes = [0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1];
let res = 0;
while (left <= right) res += primes[countOnes(left++)];
return res;
}
```
```javascript []
function countPrimeSetBits(left, right) {
const countOnes = (num) => {
let count = 0;
for (const b of num.toString(2)) count += +(b === '1');
return count;
};
const primes = [0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1];
let res = 0;
while (left <= right) res += primes[countOnes(left++)];
return res;
}
``` | 1 | 0 | ['Array', 'Math', 'Bit Manipulation', 'Memoization', 'Counting', 'Iterator', 'TypeScript', 'JavaScript'] | 0 |
prime-number-of-set-bits-in-binary-representation | Optimized Approach with Bit Manipulation | JAVA | Bit Manipulation | optimized-approach-with-bit-manipulation-63rx | IntuitionThe problem requires us to count numbers in a given range[left, right]where the number of set bits in their binary representation is a prime number.My | tNPecHTXEY | NORMAL | 2025-02-24T01:47:46.777400+00:00 | 2025-02-24T01:47:46.777400+00:00 | 119 | false |
# Intuition
The problem requires us to count numbers in a given range `[left, right]` where the number of set bits in their binary representation is a prime number.
My first thought was:
1. Iterate through each number in the range.
2. Count the number of `1`s (set bits) in its binary representation.
3. Check if the count is a prime number.
4. If it is prime, increment the result count.
# Approach
1. **Iterate through each number** from `left` to `right`.
2. **Count the set bits** using Brian Kernighan’s algorithm (`n = n & (n - 1)`) which efficiently counts set bits in `O(log n)`.
3. **Check if the count is prime** using a simple function that iterates from `1` to `n` and counts divisors.
4. **Keep track of valid numbers** and return the final count.
# Complexity
- **Time complexity:**
- Counting bits takes `O(log n)`, and checking if a number is prime takes `O(n)`.
- Since we repeat this for each number in the range `[left, right]`, worst case, it's **O(R log R + R√log R)** where `R = right - left`.
- Given constraints, this is efficient.
- **Space complexity:**
- **O(1)**, as we use only a few integer variables and no extra data structures.
# Code
```java
class Solution {
public int countPrimeSetBits(int left, int right) {
int result = 0;
for (int i = left; i <= right; i++) {
int bits = countBits(i);
if (isPrime(bits)) {
result++;
}
}
return result;
}
// Brian Kernighan's algorithm to count set bits
public int countBits(int n) {
int cnt = 0;
while (n != 0) {
n = n & (n - 1);
cnt++;
}
return cnt;
}
// Function to check if a number is prime
public boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
}
| 1 | 0 | ['Math', 'Bit Manipulation', 'Java'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.