Dynamic Programming21 sections · 916 units
Open in Course

Challenge: K Consecutive Ones

Generalizing the constraint

What if we allow up to k1k-1 consecutive 1s, but not kk or more? Track the last k1k-1 digits, not just the last one. State: (pos,tight,lastKDigits)(pos, tight, lastKDigits) where lastKDigitslastKDigits is a bitmask of the last k1k-1 positions. Transition: shift the mask left, add new digit, check if all kk digits are 1 (invalid). For k=3k = 3 in base 10: track last 2 digits. State space: O(logN210k1)O(\log N \cdot 2 \cdot 10^{k-1}). Gets expensive for large kk.

Time complexity: O(logN210k1)O(\log N \cdot 2 \cdot 10^{k-1}). Space complexity: O(logN210k1)O(\log N \cdot 2 \cdot 10^{k-1}) for the dp table.