Count K-Reducible Numbers Less Than N - Problem

You are given a binary string s representing a number n in its binary form. You are also given an integer k.

An integer x is called k-reducible if performing the following operation at most k times reduces it to 1:

  • Replace x with the count of set bits in its binary representation.

For example, the binary representation of 6 is "110". Applying the operation once reduces it to 2 (since "110" has two set bits). Applying the operation again to 2 (binary "10") reduces it to 1 (since "10" has one set bit).

Return an integer denoting the number of positive integers less than n that are k-reducible. Since the answer may be too large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: s = "111", k = 1
Output: 3
💡 Note: n = 7 in decimal. Check numbers 1-6: 1 (already 1, 0 steps), 2 (binary "10", 1 bit, 1 step), 3 (binary "11", 2 bits → 1, 1 step), 4 (binary "100", 1 bit, 1 step), 5 (binary "101", 2 bits → 1, 1 step), 6 (binary "110", 2 bits → 1, 1 step). Numbers 1,2,3,4,5,6 all need ≤1 step, but we need exactly the count. Actually: 1(0 steps), 2(1 step: 2→1), 3(2 steps: 3→2→1). So 1,2 are 1-reducible. Wait, let me recalculate: 3 has 2 bits, 2→1 is 1 step. So 1,2,3 are all 1-reducible. Answer is 3.
Example 2 — Larger k
$ Input: s = "1000", k = 2
Output: 6
💡 Note: n = 8 in decimal. Check 1-7: All numbers 1-7 can be reduced to 1 in at most 2 steps, except maybe some. Most small numbers are 2-reducible, so answer is 6.
Example 3 — Small Case
$ Input: s = "11", k = 1
Output: 2
💡 Note: n = 3 in decimal. Check 1,2: 1 needs 0 steps, 2 needs 1 step (2→1). Both are 1-reducible.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of only '0' and '1'
  • s does not have leading zeros
  • 1 ≤ k ≤ 5

Visualization

Tap to expand
K-Reducible Numbers: s="111", k=1Inputs = "111"k = 1n = 7Reduction Process (check 1,2,3,4,5,6)1: already 1 (0 steps) ✓2: 10₂ → 1 bit → 1 (1 step) ✓3: 11₂ → 2 bits → 10₂ → 1 bit → 1 (2 steps) ✗4: 100₂ → 1 bit → 1 (1 step) ✓5: 101₂ → 2 bits → 10₂ → 1 bit → 1 (2 steps) ✗6: 110₂ → 2 bits → 10₂ → 1 bit → 1 (2 steps) ✗Output31-reducible: 1,2,4Key Insight: Reduction StepsMost numbers reduce quickly. For k=1, only numbers with ≤1 bit orpowers of 2 (single bit) qualify as 1-reducibleAnswer: Count of positive integers < n that are k-reducibleResult: 3
Understanding the Visualization
1
Input
Binary string s="111" (n=7), k=1
2
Process
Check each number 1-6 for k-reducibility
3
Output
Count of k-reducible numbers: 3
Key Takeaway
🎯 Key Insight: Precompute reduction steps for bit counts, then use digit DP to count numbers with k-reducible bit counts efficiently
Asked in
Google 15 Meta 12
8.5K Views
Medium Frequency
~45 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen