#3621
Number of Integers With Popcount-Depth Equal to K I
HardMathDynamic ProgrammingBit ManipulationCombinatoricsDynamic ProgrammingBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use digit dynamic programming to count valid integers based on their binary representation and precomputed depths.
⚙️
Algorithm
3 steps- 1Step 1: Precompute popcount-depth for all integers from 0 to 64.
- 2Step 2: Use dynamic programming to count integers with exactly k ones in their binary representation while ensuring they do not exceed n.
- 3Step 3: Return the count of integers with the desired popcount-depth.
solution.py1 lines
1def precompute_depths(): depths = [0] * 65; for i in range(65): x = i; while x > 1: x = bin(x).count('1'); depths[i] += 1; return depths; def count_with_depth(n, k): depths = precompute_depths(); dp = [[0] * (k + 1) for _ in range(65)]; dp[0][0] = 1; for i in range(64): for j in range(k + 1): dp[i + 1][j] = dp[i][j]; if j > 0: dp[i + 1][j] += dp[i][j - 1]; return dp[64][k];ℹ
Complexity note: Dynamic programming allows us to efficiently count valid integers without direct iteration.
- 1Popcount-depth reduces the problem to counting set bits.
- 2Dynamic programming can optimize counting based on binary representation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.