Skip to the solution
HardDSA9 min read

What is bitmask dynamic programming?

384 views

The problem

Question presented to candidate: "What is bitmask dynamic programming? Explain when you would reach for it, describe the state for a classic problem such as assigning n workers to n jobs or the travelling salesman problem, and show me what it looks like in Python."

What a strong answer should cover:

  • A bitmask is an integer used as a set (bit i = element i); with n elements there are 2ⁿ masks, so it fits when n is small (about 20 or less).
  • The condition that makes it valid: the future depends only on which elements are used, not the order — replacing n! orders with 2ⁿ subsets.
  • Concrete states: dp[mask] for assignment (next worker = popcount), dp[mask][last] for TSP (Held–Karp, O(n² · 2ⁿ) time, O(n · 2ⁿ) space).
  • Fill order by increasing mask, the core bit operations, and submask enumeration with its 3ⁿ total cost.
  • Python details: unbounded int masks (no overflow), operator precedence (mask >> i & 1 is fine), int.bit_count() (3.10+) or bin(m).count('1'), and that Python loops over 2ⁿ · n states are slow, so keep n ≤ about 16–18.

Code / implementation expected: Optional — a short dp[mask] assignment or dp[mask][last] TSP in Python is a strong way to show you mean it.

  • dsa
  • dynamic-programming
  • bitmask

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read · 14 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonMask operations and the assignment problem with dp[mask]
PythonHeld-Karp travelling salesman with dp[mask][last]
PythonSubmask enumeration, the 3^n count, and fewest elevator trips

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 150 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

Median of two sorted arrays in O(log(min(m,n))) — how does the partition trick work?

Continue