Dynamic Programming21 sections · 915 units
Open in Course

Challenge: K Consecutive Ones

Generalizing the constraint

What if we allow up to k−1k-1 consecutive 1s, but not kk or more? Track the last k−1k-1 digits, not just the last one. State: (pos,tight,lastKDigits)(pos, tight, lastKDigits) where lastKDigitslastKDigits is a bitmask of the last k−1k-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(log⁡N⋅2⋅10k−1)O(\log N \cdot 2 \cdot 10^{k-1}). Gets expensive for large kk.

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