DSA
    advanced

    Bitmask DP (State Compression)

    Bitmask DP (State Compression)

    Use bits to represent subset states, enabling DP over all subsets efficiently. Essential for Travelling Salesman, subset selection, and assignment problems.

    ⏱ O(2^n × n)
    💾 O(2^n)
    Ready
    Current Mask
    C0
    1
    C1
    0
    C2
    0
    C3
    0
    0001 = 1
    Current City
    0
    Phase
    Initialize
    Cities + Costs
    C0C1C2C310152530
    Visited: C0

    TSP on 4 cities. State: dp[mask][city] = min cost visiting cities in 'mask', ending at 'city'. Start: dp[0001][0]=0.

    50%
    Live Variables
    n4
    startCity0
    states16

    Subsets as integers

    Sort

    Sort each bitmask expression by what it does to the subset.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    Test membership

    Drop items here

    Add an element

    Drop items here

    Remove an element

    Drop items here
    6 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    How do you iterate over all subsets of a bitmask m?

    The short version

    Imagine tracking which cities a salesman has visited using light switches. Each switch ON/OFF represents visited/not visited. Instead of storing lists, you store a single number whose binary bits encode the entire state.

    In more depth

    Subsets as Numbers

    A bitmask of n bits can represent all 2^n subsets of n elements.

    Bit i = 1 means element i is included
    Bit i = 0 means element i is excluded

    Common Operations:

    Check if i in mask: mask & (1 << i)
    Add i to mask: mask | (1 << i)
    Remove i from mask: mask & ~(1 << i)
    Iterate subsets: for (s = m; s > 0; s = (s-1) & m)

    TSP Pattern:

    dp[mask][i] = min cost to visit cities in 'mask' ending at city i

    Key Gotchas:

    Works for n ≤ 20 (2^20 ≈ 1 million states)
    Don't forget the empty subset when iterating
    Watch for signed vs unsigned integer issues

    When to reach for this

    • Visit all nodes exactly once (TSP/Hamiltonian Path)
    • Select k items from n with complex constraints
    • n is small (≤ 20) and need to consider all subsets
    • Keywords: 'all possible subsets', 'assignment problem'

    Interview Questions

    Two Sigma
    Airbnb
    Microsoft
    Palantir
    Citadel
    Facebook
    Uber
    Bloomberg
    Google
    Amazon
    Two Sigma

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required