Count K-Reducible Numbers Less Than N - Problem

You are given a binary string s representing a positive integer n in binary form, and an integer k.

A positive integer x is called k-reducible if you can reduce it to 1 by performing the following operation at most k times:

Replace x with the count of set bits (1s) in its binary representation.

Example walkthrough: Consider the number 6 with binary representation "110":

  • Operation 1: 6 โ†’ 2 (since "110" has 2 set bits)
  • Operation 2: 2 โ†’ 1 (since "10" has 1 set bit)

So 6 is 2-reducible because it takes exactly 2 operations to reach 1.

Your task is to count how many positive integers less than n are k-reducible. Since the answer can be very large, return it modulo 109 + 7.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "111", k = 1
โ€บ Output: 3
๐Ÿ’ก Note: Numbers less than 7 ("111"): 1,2,3,4,5,6. Check each: 1โ†’0 steps (โœ“), 2โ†’1 step (โœ“), 3โ†’2 steps (โœ—), 4โ†’2 steps (โœ—), 5โ†’3 steps (โœ—), 6โ†’2 steps (โœ—). Only 1,2,3 are 1-reducible, so answer is 3.
example_2.py โ€” Higher k
$ Input: s = "1000", k = 2
โ€บ Output: 6
๐Ÿ’ก Note: Numbers less than 8: 1,2,3,4,5,6,7. With k=2: 1โ†’0 steps (โœ“), 2โ†’1 step (โœ“), 3โ†’2 steps (โœ“), 4โ†’2 steps (โœ“), 5โ†’3 steps (โœ—), 6โ†’2 steps (โœ“), 7โ†’3 steps (โœ—). So 1,2,3,4,6 are 2-reducible, answer is 6.
example_3.py โ€” Edge Case
$ Input: s = "1", k = 1
โ€บ Output: 0
๐Ÿ’ก Note: Numbers less than 1: none. Answer is 0.

Constraints

  • 1 โ‰ค |s| โ‰ค 105
  • s consists only of the digits '0' and '1'
  • s does not have leading zeros
  • 1 โ‰ค k โ‰ค 105
  • The binary string can represent numbers up to 2100000
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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