AdvancedAbout 40 min

    Bitmask DP (State Compression)

    Read the full article on Substack

    7 min read.

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

    Think of it this way: 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.

    1015203525300123
    end 0end 1end 2end 3000100110101011110011011110111110∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞

    Start at city 0 with only city 0 visited: dp[0001][0] = 0.

    1/17

    Check your understanding

    Answer from memory before you scroll back up. Pulling an idea out of your head is what makes it stay there.

    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

    Quiz

    20 questions
    Question 1 of 20
    Score: 0

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

    Done with this lesson?

    Sign in free to keep your progress, streak and quiz scores.

    Keep going