Dynamic Programming21 sections · 916 units
Open in Course

Why Bitmasks Work

Compact state

A profile for nn rows is a sequence of nn bits. Instead of storing an array of booleans, you compress this into a single integer from 00 to 2n12^n - 1.

For example, with n=3n = 3, profile 55 (binary 101101) means rows 00 and 22 have protruding cells, while row 11 is clear. This lets you use dp[col][mask]dp[col][mask] where maskmask ranges over all profiles. Bitmasks make state transitions fast: you can check and modify individual bits with AND, OR, and XOR operations in constant time.