Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Dynamic Programming

Bitmask DP

O(2ⁿ · n)

Encode the set of used/visited elements as an integer bitmask and memoize over (mask, position).

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
Learn firstBit Tricks & BitmaskingSubsets / Permutations / Combinations1D / Fibonacci-style
0%
mastery
0/16 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Tiny n (<= ~20, sometimes 15-16 with an extra factor); visit/assign/order everything: TSP, Hamiltonian path, k-partition.

  1. 1Brute force

    Try all n! orders.

  2. 2The observation

    n! orders collapse to 2n subsets: the future depends only on the set used (and the last item).

  3. 3Why it works

    dp[mask][last] is optimal over orderings of exactly the items in mask, ending at last.

Reach for it when

  • +visit/assign/order a small set
  • +Hamiltonian path / TSP

Not when

  • ×n > ~25, 2ⁿ blows upuse Meet in the middle, or greedy
  • ×Items are interchangeable, so counts sufficeuse Knapsack-style DP over counts

Practice

Next · Foundation

Can I Win

The set of used numbers fully determines the state.

0/16 solved
  • Can I WinFoundationFoundationMedium
  • Partition to K Equal Sum SubsetsApply it · dp[mask] = fill of current bucket.Apply itAmazon, CitadelMedium
  • Hamiltonian FlightsOne change · Hamiltonian paths count.One changeCSESHard
  • Find the Shortest SuperstringOne change · TSP with overlap costs plus reconstruction.One changeHard
  • Shortest Path Visiting All NodesTwists · Revisits allowed; edges unweighted.TwistsHard
  • Elevator RidesBranches · State holds a pair (rides, last load).BranchesCSESMedium
  • Maximum Students Taking ExamBranches · Masks are rows of a grid.BranchesHard
  • Parallel Courses IIAdvanced · Greedy topological picking is wrong.AdvancedHard
  • Counting TilingsMastery checkMastery checkCSESHard
  • SOS Bit ProblemCSESMedium
  • And Subset CountCSESHard
  • Compatible NumbersCodeforces2200

Pitfalls

Classic bugs

  • !Mixing up 'mask of used' with 'mask of available': pick one meaning and keep it in every transition.
  • !Increasing mask order is a valid fill order: adding a bit always makes a bigger number, so sources are done first.
Go deepervariants and techniques · 6 combinations · resources

Variants and techniques

  • Sum over Subsets (SOS) DPFor every mask compute an aggregate over all its submasks (or supermasks) in O(B * 2^B) by prefix-summing one bit dimension at a time.

Combinations

  • Graph BFS / DFS+Bitmask DP

    shortest walk visiting all nodes/keys with n <= 12-20

    Graph BFS / DFS:
    BFS over moves
    Bitmask DP:
    encodes visited set into the state

    Shortest Path Visiting All Nodes

  • Bitmask DP+String Matching (KMP / Z / Rabin-Karp)

    shortest superstring containing all words (n <= 12)

    Bitmask DP:
    TSP over strings
    String Matching (KMP / Z / Rabin-Karp):
    pairwise overlaps; with at most 12 short words brute force is enough, borders (KMP) only matter at larger sizes

    Find the Shortest Superstring

  • Sum over Subsets (SOS) DP+Bit Tricks & Bitmasking

    for each x count y with x | y == x, x & y == y, or x & y == 0

    Sum over Subsets (SOS) DP:
    aggregates over submasks for all masks
    Bit Tricks & Bitmasking:
    mask representation

    SOS Bit ProblemCompatible Numbers

  • Combinatorial Game Theory (minimax, Nim, Sprague-Grundy)+Bitmask DP

    two players pick from a small pool (n <= 20) without replacement

    Combinatorial Game Theory (minimax, Nim, Sprague-Grundy):
    a state is winning if some move leads to a losing state
    Bitmask DP:
    the set of used numbers is the state

    Can I Win

  • Digit DP+Bitmask DP

    count numbers <= N with all distinct (or repeated) digits

    Digit DP:
    the tight-prefix walk over the digits of N
    Bitmask DP:
    mask of digits already used

    Count Special IntegersNumbers With Repeated Digits

  • Randomised Sampling Arguments+Sum over Subsets (SOS) DP

    find the largest set of items liked by at least half the people, with m <= 60 items but <= 15 liked per person

    Randomised Sampling Arguments:
    a random friend belongs to the optimal half-liked set with probability >= 1/2
    Sum over Subsets (SOS) DP:
    for that friend's <= 15 liked currencies, count supersets over masks

    Love-Hate

Resources

  • DP lecture notesErrichto · video
  • AtCoder Educational DP ContestAtCoder · sheet
  • Introduction to DPUSACO Guide · course
  • Dynamic Programming PatternsLeetCode discuss · article
  • Dynamic Programming playlistAditya Verma · video
  • Bitmask DPUSACO Guide · course
  • Digit DPCodeforces · blog
State Machine DP (Stocks)Digit DP
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial