LeetCode #3621 — HARD

Number of Integers With Popcount-Depth Equal to K I

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

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.

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 <= 1015
  • 0 <= k <= 5
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem 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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Math · Dynamic Programming · Bit Manipulation

Example 1

4
1

Example 2

7
2

Related Problems

  • Find Pattern in Infinite Stream II (find-pattern-in-infinite-stream-ii)
Step 02

Core Insight

What unlocks the optimal approach

  • Use digit dynamic programming on the binary representation of <code>n</code>: let <code>dp[pos][ones][tight]</code> = number of ways to choose bits from the most significant down to position <code>pos</code> with exactly <code>ones</code> ones so far, where <code>tight</code> indicates whether you're still matching the prefix of <code>n</code>.
  • Precompute <code>depth[j]</code> for all <code>j</code> from <code>0</code> to <code>64</code> by repeatedly applying <code>popcount(j)</code> until you reach <code>1</code>.
  • After your DP, let <code>dp_final[j]</code> be the count of numbers <= <code>n</code> that have exactly <code>j</code> ones; the answer is the sum of all <code>dp_final[j]</code> for which <code>depth[j] == k</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

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
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × m)
Space
O(n × m)

Approach Breakdown

RECURSIVE
O(2ⁿ) time
O(n) space

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.

DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space

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.

Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

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.

State misses one required dimension

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.