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 two integers n and k.
For any positive integer x, define the following sequence:
p0 = xpi+1 = popcount(pi) for all i >= 0, where popcount(y) is the number of set bits (1's) in the binary representation of y.This sequence will eventually reach the value 1.
The popcount-depth of x is defined as the smallest integer d >= 0 such that pd = 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 <= 10150 <= k <= 5Problem summary: You are given two integers n and k. For any positive integer x, define the following sequence: p0 = x pi+1 = popcount(pi) for all i >= 0, where popcount(y) is the number of set bits (1's) in the binary representation of y. This sequence will eventually reach the value 1. The popcount-depth of x is defined as the smallest integer d >= 0 such that pd = 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math · Dynamic Programming · Bit Manipulation
4 1
7 2
find-pattern-in-infinite-stream-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3621: Number of Integers With Popcount-Depth Equal to K I
// Auto-generated Java example from go.
class Solution {
public void exampleSolution() {
}
}
// Reference (go):
// // Accepted solution for LeetCode #3621: Number of Integers With Popcount-Depth Equal to K I
// package main
//
// import (
// "math/bits"
// "strconv"
// )
//
// // https://space.bilibili.com/206214
// func popcountDepth(n int64, k int) (ans int64) {
// if k == 0 {
// return 1
// }
//
// // 注:也可以不转成字符串,下面 dfs 用位运算取出 n 的第 i 位
// // 但转成字符串的通用性更好
// s := strconv.FormatInt(n, 2)
// m := len(s)
// if k == 1 {
// return int64(m - 1)
// }
//
// memo := make([][]int64, m)
// for i := range memo {
// memo[i] = make([]int64, m+1)
// for j := range memo[i] {
// memo[i][j] = -1
// }
// }
//
// var dfs func(int, int, bool) int64
// dfs = func(i, left1 int, isLimit bool) (res int64) {
// if i == m {
// if 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
// }
//
// f := make([]int, m+1)
// for i := 1; i <= m; i++ {
// f[i] = f[bits.OnesCount(uint(i))] + 1
// if f[i] == k {
// // 计算有多少个二进制数恰好有 i 个 1
// ans += dfs(0, i, true)
// }
// }
// return
// }
// Accepted solution for LeetCode #3621: Number of Integers With Popcount-Depth Equal to K I
package main
import (
"math/bits"
"strconv"
)
// https://space.bilibili.com/206214
func popcountDepth(n int64, k int) (ans int64) {
if k == 0 {
return 1
}
// 注:也可以不转成字符串,下面 dfs 用位运算取出 n 的第 i 位
// 但转成字符串的通用性更好
s := strconv.FormatInt(n, 2)
m := len(s)
if k == 1 {
return int64(m - 1)
}
memo := make([][]int64, m)
for i := range memo {
memo[i] = make([]int64, m+1)
for j := range memo[i] {
memo[i][j] = -1
}
}
var dfs func(int, int, bool) int64
dfs = func(i, left1 int, isLimit bool) (res int64) {
if i == m {
if 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
}
f := make([]int, m+1)
for i := 1; i <= m; i++ {
f[i] = f[bits.OnesCount(uint(i))] + 1
if f[i] == k {
// 计算有多少个二进制数恰好有 i 个 1
ans += dfs(0, i, true)
}
}
return
}
# Accepted solution for LeetCode #3621: Number of Integers With Popcount-Depth Equal to K I
#
# @lc app=leetcode id=3621 lang=python3
#
# [3621] Number of Integers With Popcount-Depth Equal to K I
#
# @lc code=start
import math
class Solution:
def popcountDepth(self, n: int, k: int) -> int:
if k == 0:
# The only number with depth 0 is 1.
# Since range is [1, n] and n >= 1, the answer is 1.
return 1
# Precompute depths for small numbers.
# Max n is 10^15, which is less than 2^50.
# The maximum popcount for a number <= 10^15 is roughly 50.
# We can compute depths up to 60 to be safe.
depth_map = {}
depth_map[1] = 0
# Function to get depth for small numbers recursively
def get_depth(val):
if val in depth_map:
return depth_map[val]
# Recursive step: depth(x) = 1 + depth(popcount(x))
# popcount(val) will be strictly less than val for val > 1
d = 1 + get_depth(val.bit_count())
depth_map[val] = d
return d
# Fill depth map for possible popcounts (1 to 60)
for i in range(1, 61):
get_depth(i)
# We are looking for x in [1, n] such that depth(x) == k.
# This is equivalent to depth(popcount(x)) == k - 1.
# Let c = popcount(x). Then we need depth(c) == k - 1.
# Since x <= n < 2^60, c will be between 1 and 60.
target_popcounts = []
for c in range(1, 61):
if depth_map[c] == k - 1:
target_popcounts.append(c)
if not target_popcounts:
return 0
# Function to count integers in [1, num] with exactly `cnt` set bits.
# Using combinatorics logic (Digit DP style without memoization table).
def count_with_bits(num, cnt):
if cnt < 0:
return 0
if num == 0:
return 0
s = bin(num)[2:]
length = len(s)
res = 0
current_bits = 0
for i in range(length):
if s[i] == '1':
# If we put '0' at this position:
# Remaining positions: length - 1 - i
# Bits needed: cnt - current_bits
remaining_len = length - 1 - i
needed = cnt - current_bits
if 0 <= needed <= remaining_len:
res += math.comb(remaining_len, needed)
# Now assume we put '1' at this position and continue
current_bits += 1
# Check the number itself
if current_bits == cnt:
res += 1
return res
total_count = 0
for c in target_popcounts:
total_count += count_with_bits(n, c)
return total_count
# @lc code=end
// Accepted solution for LeetCode #3621: Number of Integers With Popcount-Depth Equal to K I
// Rust example auto-generated from go 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 (go):
// // Accepted solution for LeetCode #3621: Number of Integers With Popcount-Depth Equal to K I
// package main
//
// import (
// "math/bits"
// "strconv"
// )
//
// // https://space.bilibili.com/206214
// func popcountDepth(n int64, k int) (ans int64) {
// if k == 0 {
// return 1
// }
//
// // 注:也可以不转成字符串,下面 dfs 用位运算取出 n 的第 i 位
// // 但转成字符串的通用性更好
// s := strconv.FormatInt(n, 2)
// m := len(s)
// if k == 1 {
// return int64(m - 1)
// }
//
// memo := make([][]int64, m)
// for i := range memo {
// memo[i] = make([]int64, m+1)
// for j := range memo[i] {
// memo[i][j] = -1
// }
// }
//
// var dfs func(int, int, bool) int64
// dfs = func(i, left1 int, isLimit bool) (res int64) {
// if i == m {
// if 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
// }
//
// f := make([]int, m+1)
// for i := 1; i <= m; i++ {
// f[i] = f[bits.OnesCount(uint(i))] + 1
// if f[i] == k {
// // 计算有多少个二进制数恰好有 i 个 1
// ans += dfs(0, i, true)
// }
// }
// return
// }
// Accepted solution for LeetCode #3621: Number of Integers With Popcount-Depth Equal to K I
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// Reference (go):
// // Accepted solution for LeetCode #3621: Number of Integers With Popcount-Depth Equal to K I
// package main
//
// import (
// "math/bits"
// "strconv"
// )
//
// // https://space.bilibili.com/206214
// func popcountDepth(n int64, k int) (ans int64) {
// if k == 0 {
// return 1
// }
//
// // 注:也可以不转成字符串,下面 dfs 用位运算取出 n 的第 i 位
// // 但转成字符串的通用性更好
// s := strconv.FormatInt(n, 2)
// m := len(s)
// if k == 1 {
// return int64(m - 1)
// }
//
// memo := make([][]int64, m)
// for i := range memo {
// memo[i] = make([]int64, m+1)
// for j := range memo[i] {
// memo[i][j] = -1
// }
// }
//
// var dfs func(int, int, bool) int64
// dfs = func(i, left1 int, isLimit bool) (res int64) {
// if i == m {
// if 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
// }
//
// f := make([]int, m+1)
// for i := 1; i <= m; i++ {
// f[i] = f[bits.OnesCount(uint(i))] + 1
// if f[i] == k {
// // 计算有多少个二进制数恰好有 i 个 1
// ans += dfs(0, i, true)
// }
// }
// return
// }
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.