Count K-Reducible Numbers Less Than N
Hard
Companies
Hint
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.
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 <= 800
s has no leading zeros.
s consists only of the characters '0' and '1'.
1 <= k <= 5
give cpp answer for the above problem in following function :
class Solution {
public:
int countKReducibleNumbers(string s, int k) {
code
}
};
Assistant
To solve the problem of counting the number of k-reducible numbers less than a given number ( n ) represented in binary string s, we can break down the solution into several key steps:
Understanding k-Reducible Numbers:
A number ( x ) is k-reducible if, by iteratively replacing ( x ) with the count of set bits in its binary representation, it can be reduced to 1 within ( k ) operations.
For example, ( x = 6 ) in binary is "110". Performing the operation once, we get the count of set bits, which is 2 ("10"). Performing it again reduces 2 to 1, making it 2-reducible.
Precomputing the Number of Steps:
We define steps[x] as the number of operations required to reduce ( x ) to 1.
For ( x = 1 ), steps[x] = 0 since it's already 1.
For other values, steps[x] = 1 + steps[\text{popcount}(x)], where popcount(x) is the number of set bits in ( x ).
Building the Set of Valid Popcounts:
To determine if a number is k-reducible, we need to know if its popcount is within a certain range that allows it to be reduced to 1 within ( k ) operations.
We create a set ( S ) where ( S = { c \mid \text{steps}[c] \leq k-1 } ). This helps in determining if a number ( x ) is k-reducible by checking if the popcount of ( x ) lies in ( S ).
Digit Dynamic Programming (DP):
We implement a digit DP approach to count the number of valid numbers less than ( n ) (given by the binary string s) that have their popcounts in set ( S ).
The key idea is to traverse through each bit of the binary string and decide whether to set the current bit to 0 or 1, ensuring that the count of set bits remains within our constraints.
We use memoization to store intermediate results and avoid redundant calculations.
Handling Edge Cases:
Specifically, when ( n = 1 ), there are no positive integers less than 1, so the result is 0.
We also handle cases where the binary string needs to be decremented by 1 to account for the strict inequality ( x < n ).
Below is the complete C++ implementation based on the above strategy:
cpp
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countKReducibleNumbers(string s, int k) {
// Helper function to compute steps[x] with memoization
// steps[x] = number of steps to reduce x to 1 via popcount operations
// steps[1] =0
// steps[x] =1 + steps[popcount(x)] for x >1
// Precompute steps[x] for x up to 1000
vector<int> steps(1001, -1);
function<int(int)> get_steps = [&](int x) -> int {
if (x ==1) return 0;
if (steps[x] !=-1) return steps[x];
if(x ==0) return INT32_MAX; // undefined, but x >=1
int c = __builtin_popcount(x);
if(c ==0) return INT32_MAX; // cannot reduce to 1
int sub_steps = get_steps(c);
if(sub_steps == INT32_MAX) return INT32_MAX;
steps[x] =1 + sub_steps;
return steps[x];
};
for(int x=1; x<=1000; x++) {
if (steps[x]==-1){
get_steps(x);
}
}
// Build S = {c | steps[c] <=k-1}
vector<bool> S(1001, false);
for(int x=1; x<=1000; x++) {
if (steps[x] != INT32_MAX && steps[x] <=k-1){
S[x] =true;
}
}
// Helper function to subtract one from binary string
auto subtract_one = [&](const string& s) -> string {
string res = s;
int i = res.length() -1;
// Perform subtraction
while(i >=0 && res[i] == '0'){
res[i] = '1';
i--;
}
if(i >=0){
res[i] = '0';
}
// If all bits were '0', it becomes all '1's, but since s has no leading zeros and n >=1, this should not happen
return res;
};
// If s is "0", subtract_one is not valid, but constraints say s has at least '1'
string s_prev = subtract_one(s);
// Now, perform digit DP on s_prev to count x <=s_prev with popcount(x) in S and x >=1
int L = s_prev.length();
// Initialize memo
// dp[pos][count][tight]
// Use memoization with -1
// To optimize memory, use a 2D memo since tight is either 0 or 1
// However, to keep it simple, use 3D vector
// Since L <=800, count <=800, tight=0/1, total states = 800 *800 *2 =1.28e6
// Initialize memo with -1
// Use a vector of vectors of vectors
// To save memory, use a memo table with default values as -1
// Implement as a 2D vector with tight states separated
// Alternatively, use a map with key as (pos, count, tight)
// But here, implement with a 3D vector
// To prevent stack overflow, implement DP iteratively or use memoization with recursion
// Here, use recursion with memo
const int MOD = 1e9+7;
// Initialize memo table with -1
// Using a large vector may cause stack issues, use memoization via a map or flat array
// Here, use a 2D vector for each tight state
// Implement as a single 1D array with pos * 1001 * 2
// Initialize memo with -1
vector<vector<vector<long long>>> memo_vec(L+1, vector<vector<long long>>(1001, vector<long long>(2, -1)));
// Define the DP function
function<long long(int, int, bool)> dfs = [&](int pos, int count, bool tight) -> long long {
if (pos == L){
if (S[count] && count >=1) return 1;
else return 0;
}
if (memo_vec[pos][count][tight ? 1 : 0] !=-1){
return memo_vec[pos][count][tight ?1 :0];
}
long long res=0;
int max_bit = tight ? (s_prev[pos]-'0') :1;
for(int bit=0; bit<=max_bit; bit++){
bool new_tight = tight && (bit == (s_prev[pos]-'0'));
int new_count = count + bit;
if(new_count >1000) continue; // since S is up to 1000
res += dfs(pos+1, new_count, new_tight);
res %= MOD;
}
memo_vec[pos][count][tight ?1 :0] = res;
return res;
};
// Handle the case when n=1, s_prev="0", the DP should return 0
// Run the DP
long long total = 0;
if(s_prev.find_first_not_of('0') != string::npos){
total = dfs(0, 0, true);
} else {
// s_prev is all '0's, which corresponds to x=0, but x >=1 is required
total =0;
}
return (int)(total % MOD);
}
};