Count K-Reducible Numbers Less Than N Problem
Description
LeetCode Problem 3352.
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
xwith 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 10^9 + 7.
Example 1:
Input: s = "111", k = 1
Output: 3
Explanation:
n = 7. The 1-reducible integers less than 7 are 1, 2, and 4.
Example 2:
Input: s = "1000", k = 2
Output: 6
Explanation:
n = 8. The 2-reducible integers less than 8 are 1, 2, 3, 4, 5, and 6.
Example 3:
Input: s = "1", k = 3
Output: 0
Explanation:
There are no positive integers less than n = 1, so the answer is 0.
Constraints:
1 <= s.length <= 800shas no leading zeros.sconsists only of the characters'0'and'1'.1 <= k <= 5
Solution
Approach: Digit DP
One operation replaces a number by its popcount. For x > 1, whether x is k-reducible depends only on popcount(x), so first compute steps[c], the number of operations needed to bring c down to 1, for every c up to the length of s.
Then count binary numbers smaller than s with exactly c ones, using a standard digit walk: at each 1 bit of s, put a 0 there and choose the remaining ones freely among the lower positions (a binomial coefficient). Add that count whenever c is valid, that is steps[c] + 1 <= k. The number 1 itself is excluded (it needs 0 operations and is handled by the c = 1 case on its own) and 0 is not counted. Take everything modulo 10^9 + 7.
Complexity: O(n^2) time for the precomputation and the binomials, where n is the length of s.
class Solution:
def countKReducibleNumbers(self, s: str, k: int) -> int:
MOD = 10**9 + 7
n = len(s)
# steps[c]: operations needed to turn c into 1
steps = [0] * (n + 1)
for c in range(2, n + 1):
steps[c] = steps[bin(c).count("1")] + 1
# comb[r][j]: ways to choose j ones among r free bits
comb = [[0] * (n + 1) for _ in range(n + 1)]
for r in range(n + 1):
comb[r][0] = 1
for j in range(1, r + 1):
comb[r][j] = (comb[r - 1][j - 1] + comb[r - 1][j]) % MOD
ans = 0
ones = 0 # ones in the prefix of s before position i
for i, ch in enumerate(s):
if ch == "1":
free = n - 1 - i
# put 0 here (below n), then choose the remaining bits freely
for c in range(max(ones, 1), ones + free + 1):
if steps[c] <= k - 1:
ans += comb[free][c - ones]
ones += 1
return ans % MOD