Tensorum

Dynamic Programming

1D, grid, knapsack, LCS, LIS, interval, tree, bitmask and digit DP across 24 patterns.

DSAAdvanced84 hrs24 patterns · 120 problems
0%
your progress

Core idea

Write the recursive brute force, name its parameters as the state, memoise, then convert to a table and compress dimensions if only the previous row is needed.

Reach for it when

  • Count ways, min/max cost, or feasibility over choices
  • Overlapping subproblems in the brute-force recursion
  • Sequences, grids, knapsacks, intervals, trees

Template

def lcs(a, b):
    prev = [0] * (len(b) + 1)
    for i in range(1, len(a) + 1):
        cur = [0] * (len(b) + 1)
        for j in range(1, len(b) + 1):
            cur[j] = prev[j-1] + 1 if a[i-1] == b[j-1] else max(prev[j], cur[j-1])
        prev = cur
    return prev[-1]

Complexity

States × transitions — e.g. O(n·m) for LCS, O(n·W) for knapsack.

Common pitfalls

  • A state that doesn't capture everything the future depends on
  • Wrong iteration order for 0/1 vs unbounded knapsack
  • Off-by-one between 1-indexed tables and 0-indexed strings

Recognition cues

1DGridKnapsackLCSLISState MachineIntervalPartitionTree/GraphBitmaskDigit