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 ≤ 1), 2 (binary "10", 1 bit → 1, 1 step ≤ 1), 3 (binary "11", 2 bits → 2 → 1, 2 steps > 1), 4 (binary "100", 1 bit → 1, 1 step ≤ 1), 5 (binary "101", 2 bits → 2 → 1, 2 steps > 1), 6 (binary "110", 2 bits → 2 → 1, 2 steps > 1). Numbers 1, 2, and 4 are 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
Count K-Reducible Numbers Less Than N INPUT Binary String s = "111" 1 1 1 n = 7 (decimal) k = 1 Check numbers 1 to 6: 1 2 3 4 5 6 ALGORITHM STEPS 1 Precompute Steps f(x) = steps to reach 1 2 DP on Digits dp[pos][cnt][tight] 3 Count Set Bits Track popcount in DP 4 Check Condition f(popcount) + 1 <= k Reduction Examples: 2(10) --> 1: 1 step OK 4(100) --> 1: 1 step OK 1(1) --> already 1 OK 3(11) --> 2 --> 1: 2 steps 5(101) --> 2 --> 1: 2 steps FINAL RESULT K-Reducible Numbers (k=1): 1 OK 2 OK 4 OK Not K-Reducible: 3 5 6 Output: 3 Count: {1, 2, 4} Key Insight: Use digit DP to count numbers less than n with specific popcount. Precompute f(x) = steps to reduce x to 1. A number is k-reducible if f(popcount) + 1 <= k (or popcount = 1 and k >= 1). Since max popcount is ~800, precomputation is efficient. Time: O(n * log n) for DP where n is length of binary string. TutorialsPoint - Count K-Reducible Numbers Less Than N | DP Approach
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