Number of Integers With Popcount-Depth Equal to K I Problem
Description
LeetCode Problem 3621.
You are given two integers n and k.
For any positive integer x, define the following sequence:
p_0 = xp_(i+1) = popcount(p_i)for alli >= 0, wherepopcount(y)is the number of set bits (1's) in the binary representation ofy.
This sequence will eventually reach the value 1.
The popcount-depth of x is defined as the smallest integer d >= 0 such that p_d = 1.
For example, if x = 7 (binary representation "111"). Then, the sequence is: 7 → 3 → 2 → 1, so the popcount-depth of 7 is 3.
Your task is to determine the number of integers in the range [1, n] whose popcount-depth is exactly equal to k.
Return the number of such integers.
Example 1:
Input: n = 4, k = 1
Output: 2
Explanation:
The following integers in the range [1, 4] have popcount-depth exactly equal to 1:
x Binary Sequence
2 "10" 2 → 1
4 "100" 4 → 1
Thus, the answer is 2.
Example 2:
Input: n = 7, k = 2
Output: 3
Explanation:
The following integers in the range [1, 7] have popcount-depth exactly equal to 2:
x Binary Sequence
3 "11" 3 → 2 → 1
5 "101" 5 → 2 → 1
6 "110" 6 → 2 → 1
Thus, the answer is 3.
Constraints:
1 <= n <= 10^150 <= k <= 5
Solution
Approach: Digit Counting by Number of Set Bits
Because n < 2^50, the popcount of any x <= n is at most 50, so the depth of x is 1 + depth(popcount(x)) and we can precompute the depth of every small value c in [1, 50] (with depth(1) = 0). An integer x has depth k exactly when its popcount c has depth k - 1.
So for each c with depth(c) = k - 1, count the integers in [1, n] with exactly c set bits. To do that, scan the bits of n from the top; at every set bit, the numbers that put a 0 there and then pick the remaining ones freely from the lower i bits contribute C(i, c - ones), where ones is the number of set bits taken so far. Finally add 1 if n itself has c set bits.
Two special cases: for k = 0 the answer is 1 (only x = 1), and for k = 1 we subtract 1 because x = 1 has popcount 1 but depth 0.
Complexity: O(log^2 n) time and space.
class Solution:
def popcountDepth(self, n: int, k: int) -> int:
if k == 0:
return 1
m = n.bit_length()
C = [[0] * (m + 1) for _ in range(m + 1)]
for i in range(m + 1):
C[i][0] = 1
for j in range(1, i + 1):
C[i][j] = C[i - 1][j - 1] + C[i - 1][j]
def depth(c):
d = 0
while c != 1:
c = bin(c).count("1")
d += 1
return d
def count(c):
res = ones = 0
for i in range(m - 1, -1, -1):
if n >> i & 1:
need = c - ones
if 0 <= need <= i:
res += C[i][need]
ones += 1
return res + (1 if ones == c else 0)
ans = sum(count(c) for c in range(1, m + 1) if depth(c) == k - 1)
return ans - 1 if k == 1 else ans