All Bitwise Subsets of a Number

Last Updated : 5 Aug, 2026

Given an integer n, find all the numbers that are bitwise subsets of n. A number i is considered a bitwise subset of n if all the set bits (1s) in the binary representation of i are also set in the binary representation of n i.e. (n & i == i). 

Return all such numbers i in descending order. 

Examples: 

Input: n = 5
Output: [5, 4, 1, 0]
Explanation: For all i from 0 ≤ i ≤ n.
2 is not a subset because the same bit is not set in 5
3 is also not a subset because the second bit is not set in 5
All other numbers are subset. Hence the output in descending order is: [5, 4, 1, 0].

Input: n = 1
Output: [1, 0]

Try It Yourself
redirect icon

[Naive Approach] Brute Force Approach - O(n) Time and O(1) Space

The idea is to check every number from 0 to n and check if all its set bits are also set in n, which can be verified using the condition (n & i) == i.. If i is subset, then all of its bits must be present in n also, hence we get output as i when we do AND.

  • Initialize an empty vector to store the answer.
  • Iterate through all integers i from n down to 0.
  • For each i, check whether (n & i) == i.
  • If the condition is true, add i to the answer.
  • Return the collected numbers.
C++
#include <bits/stdc++.h>
using namespace std;

vector<int> printSubsets(int n)
{
    vector<int> ans;

    // Check every number from n down to 0
    for (int i = n; i >= 0; i--)
    {
        // If i is a bitwise subset of n
        if ((n & i) == i)
            ans.push_back(i);
    }

    return ans;
}

int main()
{
    int n = 5;
    vector<int> ans = printSubsets(n);

    for (int x : ans)
        cout << x << " ";

    return 0;
}
Java
import java.util.*;

class GFG {

    static ArrayList<Integer> printSubsets(int n) {
        ArrayList<Integer> ans = new ArrayList<>();

        // Check every number from n down to 0
        for (int i = n; i >= 0; i--) {

            // If i is a bitwise subset of n
            if ((n & i) == i)
                ans.add(i);
        }

        return ans;
    }

    public static void main(String[] args) {
        int n = 5;
        ArrayList<Integer> ans = printSubsets(n);

        for (int x : ans)
            System.out.print(x + " ");
    }
}
Python
def printSubsets(n):
    ans = []

    # Check every number from n down to 0
    for i in range(n, -1, -1):

        # If i is a bitwise subset of n
        if (n & i) == i:
            ans.append(i)

    return ans

# Driver Code
if __name__ == "__main__":
    n = 5
    ans = printSubsets(n)

    print(*ans)
C#
using System;
using System.Collections.Generic;

class GFG {
    static List<int> printSubsets(int n)
    {
        List<int> ans = new List<int>();

        // Check every number from n down to 0
        for (int i = n; i >= 0; i--) {
            // If i is a bitwise subset of n
            if ((n & i) == i)
                ans.Add(i);
        }

        return ans;
    }

    static void Main()
    {
        int n = 5;
        List<int> ans = printSubsets(n);

        foreach(int x in ans) Console.Write(x + " ");
    }
}
JavaScript
function printSubsets(n)
{
    let ans = [];

    // Check every number from n down to 0
    for (let i = n; i >= 0; i--) {

        // If i is a bitwise subset of n
        if ((n & i) === i)
            ans.push(i);
    }

    return ans;
}

// Driver Code
let n = 5;
let ans = printSubsets(n);

console.log(...ans);

Output
5 4 1 0 

[Expected Approach] Iterate Over All Submasks - O(resSize) Time and O(1) Space

The idea is that every bitwise subset of n is simply a submask of n, we can directly generate all submasks using the relation (submask - 1) & n. This efficiently visits every valid bitwise subset exactly once in descending order.

Let us understand with an example of n = 13, the value of submask changes as shown below.

1101 (13), 1100 (12), 1001 (9), 1000 (8), 0101 (5), 0100 (4), 0001 (1) and 0000 (0)

How does this work.

  • After subtraction. the rightmost 1 became 0 and every bit to its right became 1.
  • The AND operation clears every bit that is not set in n
C++
#include <bits/stdc++.h>
using namespace std;

vector<int> printSubsets(int n)
{
    vector<int> ans;

    // Generate all submasks of n
    for (int submask = n; submask > 0; submask = (submask - 1) & n)
        ans.push_back(submask);

    // Add the empty subset
    ans.push_back(0);

    return ans;
}

int main()
{
    int n = 5;

    vector<int> ans = printSubsets(n);

    for (int x : ans)
        cout << x << " ";

    return 0;
}
Java
import java.util.*;

class GFG {
    static ArrayList<Integer> printSubsets(int n)
    {
        ArrayList<Integer> ans = new ArrayList<>();

        // Generate all submasks of n
        for (int submask = n; submask > 0;
             submask = (submask - 1) & n)
            ans.add(submask);

        // Add the empty subset
        ans.add(0);

        return ans;
    }

    public static void main(String[] args)
    {
        int n = 5;
        ArrayList<Integer> ans = printSubsets(n);

        for (int x : ans)
            System.out.print(x + " ");
    }
}
Python
def printSubsets(n):
    ans = []

    # Generate all submasks of n
    submask = n
    while submask > 0:
        ans.append(submask)
        submask = (submask - 1) & n

    # Add the empty subset
    ans.append(0)

    return ans


# Driver Code
if __name__ == "__main__":
    n = 5
    ans = printSubsets(n)

    print(*ans)
C#
using System;
using System.Collections.Generic;

class GFG {
    static List<int> printSubsets(int n)
    {
        List<int> ans = new List<int>();

        // Generate all submasks of n
        for (int submask = n; submask > 0;
             submask = (submask - 1) & n)
            ans.Add(submask);

        // Add the empty subset
        ans.Add(0);

        return ans;
    }

    static void Main()
    {
        int n = 5;
        List<int> ans = printSubsets(n);

        foreach(int x in ans) Console.Write(x + " ");
    }
}
JavaScript
function printSubsets(n)
{
    let ans = [];

    // Generate all submasks of n
    for (let submask = n; submask > 0;
         submask = (submask - 1) & n)
        ans.push(submask);

    // Add the empty subset
    ans.push(0);

    return ans;
}

// Driver Code
let n = 5;
let ans = printSubsets(n);

console.log(...ans);

Output
5 4 1 0 

Time Complexity: O(k), where k is the number of items in the result.
Auxiliary Space: O(1)

[Alternate Approach] Using Set Bits

The idea is to process only the set bits of n. Initially, the only bitwise subset is 0. For every set bit in n, we generate new subsets by adding that bit to all previously generated subsets. After processing all set bits, we obtain every possible bitwise subset of n.

  • Initialize the answer with 0.
  • Traverse every bit position of n.
  • If the current bit is set in n:
    Create new subsets by OR-ing the current bit with every existing subset.
    Append the newly formed subsets to the answer.
  • Reverse the answer to get the subsets in descending order.
  • Return the answer.
C++
#include <bits/stdc++.h>
using namespace std;

vector<int> printSubsets(int n)
{
    vector<int> ans = {0};

    // Process every bit of n
    for (int bit = 1; bit <= n; bit <<= 1)
    {
        // If the current bit is set
        if (n & bit)
        {
            int sz = ans.size();

            // Generate new subsets by including this bit
            for (int i = 0; i < sz; i++)
                ans.push_back(ans[i] | bit);
        }
    }

    // Return subsets in descending order
    reverse(ans.begin(), ans.end());

    return ans;
}

int main()
{
    int n = 5;
    vector<int> ans = printSubsets(n);

    for (int x : ans)
        cout << x << " ";

    return 0;
}
Java
import java.util.*;

class GFG {
    static ArrayList<Integer> printSubsets(int n)
    {
        ArrayList<Integer> ans = new ArrayList<>();
        ans.add(0);

        // Process every bit of n
        for (int bit = 1; bit <= n; bit <<= 1) {

            // If the current bit is set
            if ((n & bit) != 0) {
                int sz = ans.size();

                // Generate new subsets by including this
                // bit
                for (int i = 0; i < sz; i++)
                    ans.add(ans.get(i) | bit);
            }
        }

        // Return subsets in descending order
        Collections.reverse(ans);

        return ans;
    }

    public static void main(String[] args)
    {
        int n = 5;
        List<Integer> ans = printSubsets(n);

        for (int x : ans)
            System.out.print(x + " ");
    }
}
Python
def printSubsets(n):
    ans = [0]

    bit = 1

    # Process every bit of n
    while bit <= n:

        # If the current bit is set
        if n & bit:
            size = len(ans)

            # Generate new subsets by including this bit
            for i in range(size):
                ans.append(ans[i] | bit)

        bit <<= 1

    # Return subsets in descending order
    ans.reverse()

    return ans


# Driver Code
if __name__ == "__main__":
    n = 5
    ans = printSubsets(n)

    print(*ans)
C#
using System;
using System.Collections.Generic;

class GFG {
    static List<int> printSubsets(int n)
    {
        List<int> ans = new List<int>{ 0 };

        // Process every bit of n
        for (int bit = 1; bit <= n; bit <<= 1) {
            // If the current bit is set
            if ((n & bit) != 0) {
                int size = ans.Count;

                // Generate new subsets by including this
                // bit
                for (int i = 0; i < size; i++)
                    ans.Add(ans[i] | bit);
            }
        }

        // Return subsets in descending order
        ans.Reverse();

        return ans;
    }

    static void Main()
    {
        int n = 5;
        List<int> ans = printSubsets(n);

        foreach(int x in ans) Console.Write(x + " ");
    }
}
JavaScript
function printSubsets(n)
{
    let ans = [ 0 ];

    // Process every bit of n
    for (let bit = 1; bit <= n; bit <<= 1) {

        // If the current bit is set
        if (n & bit) {
            let size = ans.length;

            // Generate new subsets by including this bit
            for (let i = 0; i < size; i++)
                ans.push(ans[i] | bit);
        }
    }

    // Return subsets in descending order
    ans.reverse();

    return ans;
}

// Driver Code
let n = 5;
let ans = printSubsets(n);

console.log(...ans);

Output
5 4 1 0 
Comment