Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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:
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.
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 <= 800s has no leading zeros.s consists only of the characters '0' and '1'.1 <= k <= 5Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math · Dynamic Programming
"111" 1
"1000" 2
"1" 3
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3352: Count K-Reducible Numbers Less Than N
class Solution {
public int countKReducibleNumbers(String s, int k) {
Integer[][][] mem = new Integer[s.length()][s.length() + 1][2];
return count(s, 0, 0, true, k, getOps(s), mem) - 1; // - 0
}
private static final int MOD = 1_000_000_007;
// Returns the number of positive integers less than n that are k-reducible,
// considering the i-th digit, where `setBits` is the number of set bits in
// the current number, and `tight` indicates if the current digit is
// tightly bound.
private int count(String s, int i, int setBits, boolean tight, int k, int[] ops,
Integer[][][] mem) {
if (i == s.length())
return (ops[setBits] < k && !tight) ? 1 : 0;
if (mem[i][setBits][tight ? 1 : 0] != null)
return mem[i][setBits][tight ? 1 : 0];
int res = 0;
final int maxDigit = tight ? s.charAt(i) - '0' : 1;
for (int d = 0; d <= maxDigit; ++d) {
final boolean nextTight = tight && (d == maxDigit);
res += count(s, i + 1, setBits + d, nextTight, k, ops, mem);
res %= MOD;
}
return mem[i][setBits][tight ? 1 : 0] = res;
}
// Returns the number of operations to reduce a number to 0.
private int[] getOps(String s) {
int[] ops = new int[s.length() + 1];
for (int num = 2; num <= s.length(); ++num)
ops[num] = 1 + ops[Integer.bitCount(num)];
return ops;
}
}
// Accepted solution for LeetCode #3352: Count K-Reducible Numbers Less Than N
package main
import "math/bits"
// https://space.bilibili.com/206214
func countKReducibleNumbers(s string, k int) (ans int) {
const mod = 1_000_000_007
n := len(s)
memo := make([][]int, n)
for i := range memo {
memo[i] = make([]int, n)
for j := range memo[i] {
memo[i][j] = -1
}
}
var dfs func(int, int, bool) int
dfs = func(i, left1 int, isLimit bool) (res int) {
if i == n {
if !isLimit && left1 == 0 {
return 1
}
return
}
if !isLimit {
p := &memo[i][left1]
if *p >= 0 {
return *p
}
defer func() { *p = res }()
}
up := 1
if isLimit {
up = int(s[i] - '0')
}
for d := 0; d <= min(up, left1); d++ {
res += dfs(i+1, left1-d, isLimit && d == up)
}
return res % mod
}
f := make([]int, n)
for i := 1; i < n; i++ {
f[i] = f[bits.OnesCount(uint(i))] + 1
if f[i] <= k {
// 计算有多少个二进制数恰好有 i 个 1
ans += dfs(0, i, true)
}
}
return ans % mod
}
# Accepted solution for LeetCode #3352: Count K-Reducible Numbers Less Than N
class Solution:
def countKReducibleNumbers(self, s: str, k: int) -> int:
MOD = 1_000_000_007
ops = self._getOps(s)
@functools.lru_cache(None)
def dp(i: int, setBits: int, tight: bool) -> int:
"""
Returns the number of positive integers less than n that are k-reducible,
considering the i-th digit, where `setBits` is the number of set bits in
the current number, and `tight` indicates if the current digit is
tightly bound.
"""
if i == len(s):
return int(ops[setBits] < k and not tight)
res = 0
maxDigit = int(s[i]) if tight else 1
for d in range(maxDigit + 1):
nextTight = tight and (d == maxDigit)
res += dp(i + 1, setBits + d, nextTight)
res %= MOD
return res
return dp(0, 0, True) - 1 # - 0
def _getOps(self, s: str) -> int:
"""Returns the number of operations to reduce a number to 0."""
ops = [0] * (len(s) + 1)
for num in range(2, len(s) + 1):
ops[num] = 1 + ops[num.bit_count()]
return ops
// Accepted solution for LeetCode #3352: Count K-Reducible Numbers Less Than N
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3352: Count K-Reducible Numbers Less Than N
// class Solution {
// public int countKReducibleNumbers(String s, int k) {
// Integer[][][] mem = new Integer[s.length()][s.length() + 1][2];
// return count(s, 0, 0, true, k, getOps(s), mem) - 1; // - 0
// }
//
// private static final int MOD = 1_000_000_007;
//
// // Returns the number of positive integers less than n that are k-reducible,
// // considering the i-th digit, where `setBits` is the number of set bits in
// // the current number, and `tight` indicates if the current digit is
// // tightly bound.
// private int count(String s, int i, int setBits, boolean tight, int k, int[] ops,
// Integer[][][] mem) {
// if (i == s.length())
// return (ops[setBits] < k && !tight) ? 1 : 0;
// if (mem[i][setBits][tight ? 1 : 0] != null)
// return mem[i][setBits][tight ? 1 : 0];
//
// int res = 0;
// final int maxDigit = tight ? s.charAt(i) - '0' : 1;
//
// for (int d = 0; d <= maxDigit; ++d) {
// final boolean nextTight = tight && (d == maxDigit);
// res += count(s, i + 1, setBits + d, nextTight, k, ops, mem);
// res %= MOD;
// }
//
// return mem[i][setBits][tight ? 1 : 0] = res;
// }
//
// // Returns the number of operations to reduce a number to 0.
// private int[] getOps(String s) {
// int[] ops = new int[s.length() + 1];
// for (int num = 2; num <= s.length(); ++num)
// ops[num] = 1 + ops[Integer.bitCount(num)];
// return ops;
// }
// }
// Accepted solution for LeetCode #3352: Count K-Reducible Numbers Less Than N
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3352: Count K-Reducible Numbers Less Than N
// class Solution {
// public int countKReducibleNumbers(String s, int k) {
// Integer[][][] mem = new Integer[s.length()][s.length() + 1][2];
// return count(s, 0, 0, true, k, getOps(s), mem) - 1; // - 0
// }
//
// private static final int MOD = 1_000_000_007;
//
// // Returns the number of positive integers less than n that are k-reducible,
// // considering the i-th digit, where `setBits` is the number of set bits in
// // the current number, and `tight` indicates if the current digit is
// // tightly bound.
// private int count(String s, int i, int setBits, boolean tight, int k, int[] ops,
// Integer[][][] mem) {
// if (i == s.length())
// return (ops[setBits] < k && !tight) ? 1 : 0;
// if (mem[i][setBits][tight ? 1 : 0] != null)
// return mem[i][setBits][tight ? 1 : 0];
//
// int res = 0;
// final int maxDigit = tight ? s.charAt(i) - '0' : 1;
//
// for (int d = 0; d <= maxDigit; ++d) {
// final boolean nextTight = tight && (d == maxDigit);
// res += count(s, i + 1, setBits + d, nextTight, k, ops, mem);
// res %= MOD;
// }
//
// return mem[i][setBits][tight ? 1 : 0] = res;
// }
//
// // Returns the number of operations to reduce a number to 0.
// private int[] getOps(String s) {
// int[] ops = new int[s.length() + 1];
// for (int num = 2; num <= s.length(); ++num)
// ops[num] = 1 + ops[Integer.bitCount(num)];
// return ops;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.