DrawCode Algorithm Visualizer • Bit Manipulation • Medium

Power Set via Bitmasks

Tags: Bit, Subset, Bitmask, Combinatorics

1. One-Liner

Each integer mask from 0 to 2^n−1 encodes one subset: bit i means take element i.


2. The Problem It Solves

Generate subsets for brute-force small n, competitive programming, and DP over subsets (SOS DP builds on this idea).


3. The Core Idea

Nested loops: outer mask, inner bit scan to collect members—natural order Gray code can minimize transitions (see Gray code).


4. How It Works (Step-by-Step)

StepAction
1n = len(arr)
2For mask in 0..2^n-1
3For each bit i in mask, if set include arr[i]
4Collect subset

5. Dry Run Example

n=3 → 8 subsets from {} to {a,b,c} following binary masks.


6. Key Properties

PropertyDetail
Count2^n subsets
OrderBinary mask order
PruningAdd constraints inside loop

7. Where It Is Used

Domain / SystemUse
SchedulingFeasible subsets
TestingCombinatorial cases
CryptoTiny exhaustive search

8. Interview Tips

For n>20 brute force explodes—meet-in-the-middle or DP. Mention Gosper’s hack for k-bit sets.


9. Comparison with Other Algorithms

TechniqueNotes
Recursion backtrackingSame 2^n
Branch & boundPrune early
SOS DPSum over supersets

10. Complexity

----
TimeO(n · 2^n)
SpaceO(n) per subset output

Implementation Example (PYTHON)

def power_set(arr):
    n = len(arr)
    out = []
    for mask in range(1 << n):
        sub = [arr[i] for i in range(n) if mask >> i & 1]
        out.append(sub)
    return out

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer