Ctrl K

Collapsing by Counting Ones

Hard
You are given the binary representation bits of a number n (with no leading zeros) and an integer steps. A step replaces a positive integer x with the number of ones in its binary representation. For example, 13 = 1101₂ becomes 3, and 3 = 11₂ becomes 2. A number x **collapses** if it turns into 1 within at most steps steps (the number 1 itself collapses in zero steps). Count the positive integers less than n that collapse. The answer can be huge, so return it modulo 10⁹ + 7. Note that bits can be up to 800 characters long, so going through all the numbers is out of the question.
Example 1
bits="110", steps=1 → 3

The bound is 6. Only numbers with a single set bit reach 1 in one step: 1, 2 and 4.

Example 2
bits="1010", steps=2 → 8

The bound is 10. Numbers with one set bit (1, 2, 4, 8) qualify, and so do those with two (3, 5, 6, 9): they turn into 2 and then into 1. The number 7 goes 3 → 2 → 1, which takes three steps.

Example 3
bits="10", steps=5 → 1

The bound is 2; the only number below it is 1, which is already 1.

Constraints
  • 1 ≤ len(bits) ≤ 800
  • bits consists of 0 and 1 and starts with 1
  • 1 ≤ steps ≤ 5
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBalanced Digit Shuffles HardVowels Across All Pieces MediumTasters and the Spoiled Cask HardNumbers From Working Keys HardRadio Show Without Quick Repeats Hard
loading Python…
Input
bits="110", steps=1
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 40 tests on the server, hidden ones included.