{"id":708,"date":"2025-07-21T14:16:43","date_gmt":"2025-07-21T08:46:43","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=708"},"modified":"2025-07-21T14:16:48","modified_gmt":"2025-07-21T08:46:48","slug":"generate-all-subsets-using-bit-manipulation-leetcode-78","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/generate-all-subsets-using-bit-manipulation-leetcode-78\/","title":{"rendered":"Generate all Subsets using Bit Manipulation | Leetcode 78 | Python Code"},"content":{"rendered":"\n<p>Given an integer array&nbsp;<code>nums<\/code>&nbsp;of&nbsp;<strong>unique<\/strong>&nbsp;elements, return&nbsp;<em>all possible<\/em>&nbsp;<em>subsets<\/em>&nbsp;<em>(the power set)<\/em>.<\/p>\n\n\n\n<p>The solution set&nbsp;<strong>must not<\/strong>&nbsp;contain duplicate subsets. Return the solution in&nbsp;<strong>any order<\/strong>.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/subsets\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> nums = [1,2,3]<br><strong>Output:<\/strong> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> nums = [0]<br><strong>Output:<\/strong> [[],[0]]<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>1 &lt;= nums.length &lt;= 10<\/code><\/li>\n\n\n\n<li><code>-10 &lt;= nums[i] &lt;= 10<\/code><\/li>\n\n\n\n<li>All the numbers of&nbsp;<code>nums<\/code>&nbsp;are&nbsp;<strong>unique<\/strong>.<\/li>\n<\/ul>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-94f26136-6f3f-4ca8-9eab-c2f5b8d09398\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"true\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/generate-all-subsets-using-bit-manipulation-leetcode-78\/#0-optimal-approach-bitwise-masking\" style=\"\">Optimal Approach (Bitwise Masking)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/generate-all-subsets-using-bit-manipulation-leetcode-78\/#1-intuition\" style=\"\">Intuition<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/generate-all-subsets-using-bit-manipulation-leetcode-78\/#2-detailed-approach\" style=\"\">Detailed Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/generate-all-subsets-using-bit-manipulation-leetcode-78\/#3-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/generate-all-subsets-using-bit-manipulation-leetcode-78\/#4-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/generate-all-subsets-using-bit-manipulation-leetcode-78\/#5-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/generate-all-subsets-using-bit-manipulation-leetcode-78\/#6-simplifying-it\" style=\"\">Simplifying It<\/a><\/li><\/ul><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-optimal-approach-bitwise-masking\">Optimal Approach (Bitwise Masking)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition\">Intuition<\/h3>\n\n\n\n<p>Every subset can be represented by a binary number where each bit says &#8220;include this element&#8221; (1) or &#8220;skip it&#8221; (0). For an array of size n, there are 2^n possible subsets, matching numbers from 0 to (2^n &#8211; 1). For each number, check which bits are set and include those elements in the subset. It&#8217;s like using a binary code to unlock all combinations!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-detailed-approach\">Detailed Approach<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Calculate Total Subsets<\/strong>: There are 2^n subsets, so loop from 0 to (1 &lt;&lt; n) &#8211; 1.<\/li>\n\n\n\n<li><strong>Generate Subset<\/strong>: For each mask (number), check each bit position i.<\/li>\n\n\n\n<li><strong>Bit Check<\/strong>: If the i-th bit is set (mask &amp; (1 &lt;&lt; i) != 0), include nums[i] in the current subset.<\/li>\n\n\n\n<li><strong>Collect Subsets<\/strong>: Build a list for each mask and add it to the result.<\/li>\n\n\n\n<li><strong>Return Result<\/strong>: All subsets are generated in a single loop.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-code\">Code<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def subsets(self, nums: List[int]) -&gt; List[List[int]]:\n        n = len(nums)\n        total_subset = 1 &lt;&lt; n  # 2^n subsets\n        result = []            # List to store all subsets\n        \n        # Loop through each possible subset mask\n        for num in range(total_subset):\n            lst = []           # Current subset\n            # Check each bit in the mask\n            for i in range(0, n):\n                if num &amp; (1 &lt;&lt; i) != 0:\n                    lst.append(nums[i])  # Include if bit is set\n            result.append(lst)   # Add to result\n        \n        return result\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">subsets<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; List[List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        total_subset = <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> &lt;&lt; n  <\/span><span style=\"color: #6A9955\"># 2^n subsets<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        result = []            <\/span><span style=\"color: #6A9955\"># List to store all subsets<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Loop through each possible subset mask<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> num <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(total_subset):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            lst = []           <\/span><span style=\"color: #6A9955\"># Current subset<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Check each bit in the mask<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> num &amp; (<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> &lt;&lt; i) != <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    lst.append(nums[i])  <\/span><span style=\"color: #6A9955\"># Include if bit is set<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            result.append(lst)   <\/span><span style=\"color: #6A9955\"># Add to result<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> result<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-code-explanation\">Code Explanation<\/h3>\n\n\n\n<p>We calculate the total number of subsets as 2 raised to the power of n (using left shift: 1 &lt;&lt; n). Then, for each possible mask from 0 to (2^n &#8211; 1), we create a new list. For each bit position i, if the bit is set in the mask (checked with &amp; (1 &lt;&lt; i)), we add nums[i] to the list. After checking all bits for that mask, we add the list to our result. This generates all subsets efficiently without recursion.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>&nbsp;O(n * 2^n) &#8211; For each of 2^n masks, we loop n times to check bits.<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>&nbsp;O(1) &#8211; Besides the output, we use constant extra space (ignoring result space).<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-simplifying-it\">Simplifying It<\/h3>\n\n\n\n<p>This is like using a secret code (binary masks) to represent subsets. Each number from 0 to 2^n-1 is a code where &#8216;1&#8217; means &#8220;include this item.&#8221; It&#8217;s super efficient and avoids recursion, making it great for larger arrays.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Given an integer array&nbsp;nums&nbsp;of&nbsp;unique&nbsp;elements, return&nbsp;all possible&nbsp;subsets&nbsp;(the power set). The solution set&nbsp;must not&nbsp;contain duplicate subsets. Return the solution in&nbsp;any order. Here&#8217;s the [Problem Link] to begin with. Example 1: Input: nums = [1,2,3]Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] Example 2: Input: nums = [0]Output: [[],[0]] Constraints: Optimal Approach (Bitwise Masking) Intuition Every subset can be represented by a binary number<\/p>\n","protected":false},"author":1,"featured_media":709,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[31,19],"class_list":{"0":"post-708","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-intermediate","9":"tag-bit-manipulation","10":"tag-medium"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/07\/generate-all-subsets-using-bit-manipulation-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/708","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=708"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/708\/revisions"}],"predecessor-version":[{"id":711,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/708\/revisions\/711"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/709"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=708"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=708"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=708"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}