Dynamic Programming21 sections · 916 units
Open in Course

Special Integers - Walkthrough

Tracing distinct digits

Count numbers 135\leq 135 with all distinct digits. Use a bitmask to track used digits. Start: mask = 0, tight = true, started = false. Position 00: try 00 (leading zero, don't add to mask), 1 (mask |= 2).

If we chose 1 (mask = 0b10, tight = true): position 11 can be 00, 22, 33 (not 1, it's used). If we choose 33 (> limit's 3), invalid. Continue to position 22. Count paths where each digit appears at most once. Bitmask tracks usage in O(1)O(1) per transition.