Algorithms · Visualized

DP: Bitmask DP (TSP)

Dynamic Programming

Break problems into overlapping subproblems and store answers.

Bitmask DP stores which items (cities, tasks, vertices) have been used so far as a single integer whose bits flag inclusion, letting one state encode an exponential number of subsets. Time: O(2ⁿ·n²) average, O(2ⁿ·n²) for TSP-style problems worst; space: O(2ⁿ·n).

Big-O: The most-asked interview category — 35 classics here.

Bitmask DP (Traveling Salesman)

Dynamic Programming

Bitmask DP stores which items (cities, tasks, vertices) have been used so far as a single integer whose bits flag inclusion, letting one state encode an exponential number of subsets. This compact representation solves small Traveling Salesman instances exactly: dp[mask][last] = cheapest route visiting exactly the cities in mask and ending at last.

How Bitmask DP (TSP) Works

  1. Represent the state: dp[mask][last] = best cost of a route visiting exactly the cities set in mask, ending at city last.
  2. Base case: dp[1<<i][i] = 0 for every city i — a tour starting alone at i.
  3. Transition: from each defined (mask, last), extend to every unvisited city next: dp[mask|(1<<next)][next] = min(dp[mask][last] + dist(last, next)).
  4. Iterate masks in increasing numeric order so every subproblem is solved before it is needed.
  5. Final answer: min over k of dp[full][k] + dist(k, 0) — closing the tour back to the start city.

Bitmask DP (TSP) Worked Example

Input: TSP on 4 cities with distance matrix [[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]]

dp[0001][0] = 0 (start at city 0). dp[0011][1] = dp[0001][0] + dist(0,1) = 10 — visited {0,1}, ending at 1. Keep building masks: {0,1,2}, {0,1,3}, ..., up to the full mask 1111. Finally dp[1111][k] for each k, closed by dist(k,0): the minimum is 80 (0→1→3→2→0 = 10+25+30+15).

Python · Dynamic Programming Algorithms in Code
def tsp(dist):
    n = len(dist)
    full = (1 << n) - 1
    dp = [[float('inf')] * n for _ in range(1 << n)]
    for i in range(n):
        dp[1 << i][i] = 0
    for mask in range(1, full + 1):
        for last in range(n):
            if dp[mask][last] == float('inf'):
                continue
            for nxt in range(n):
                if mask & (1 << nxt):
                    continue
                nmask = mask | (1 << nxt)
                dp[nmask][nxt] = min(dp[nmask][nxt], dp[mask][last] + dist[last][nxt])
    return min(dp[full][k] + dist[k][0] for k in range(n))

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Bitmask DP (TSP) Time & Space Complexity

BestO(2ⁿ·n²)
AverageO(2ⁿ·n²)
WorstO(2ⁿ·n²) for TSP-style problems
SpaceO(2ⁿ·n)

When to Use Bitmask DP (TSP)

  • Exact TSP solutions for small n (n ≤ ~20).
  • Assignment problems — optimally matching workers to tasks.
  • Any 'subset of items processed so far' state space, e.g. DAG covers and set cover variants.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.