LeetCode #3624 — HARD

Number of Integers With Popcount-Depth Equal to K II

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 an integer array nums.

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.

You are also given a 2D integer array queries, where each queries[i] is either:

  • [1, l, r, k] - Determine the number of indices j such that l <= j <= r and the popcount-depth of nums[j] is equal to k.
  • [2, idx, val] - Update nums[idx] to val.

Return an integer array answer, where answer[i] is the number of indices for the ith query of type [1, l, r, k].

Example 1:

Input: nums = [2,4], queries = [[1,0,1,1],[2,1,1],[1,0,1,0]]

Output: [2,1]

Explanation:

i queries[i] nums binary(nums) popcount-
depth
[l, r] k Valid
nums[j]
updated
nums
Answer
0 [1,0,1,1] [2,4] [10, 100] [1, 1] [0, 1] 1 [0, 1] 2
1 [2,1,1] [2,4] [10, 100] [1, 1] [2,1]
2 [1,0,1,0] [2,1] [10, 1] [1, 0] [0, 1] 0 [1] 1

Thus, the final answer is [2, 1].

Example 2:

Input: nums = [3,5,6], queries = [[1,0,2,2],[2,1,4],[1,1,2,1],[1,0,1,0]]

Output: [3,1,0]

Explanation:

i queries[i] nums binary(nums) popcount-
depth
[l, r] k Valid
nums[j]
updated
nums
Answer
0 [1,0,2,2] [3, 5, 6] [11, 101, 110] [2, 2, 2] [0, 2] 2 [0, 1, 2] 3
1 [2,1,4] [3, 5, 6] [11, 101, 110] [2, 2, 2] [3, 4, 6]
2 [1,1,2,1] [3, 4, 6] [11, 100, 110] [2, 1, 2] [1, 2] 1 [1] 1
3 [1,0,1,0] [3, 4, 6] [11, 100, 110] [2, 1, 2] [0, 1] 0 [] 0

Thus, the final answer is [3, 1, 0].

Example 3:

Input: nums = [1,2], queries = [[1,0,1,1],[2,0,3],[1,0,0,1],[1,0,0,2]]

Output: [1,0,1]

Explanation:

i queries[i] nums binary(nums) popcount-
depth
[l, r] k Valid
nums[j]
updated
nums
Answer
0 [1,0,1,1] [1, 2] [1, 10] [0, 1] [0, 1] 1 [1] 1
1 [2,0,3] [1, 2] [1, 10] [0, 1] [3, 2]  
2 [1,0,0,1] [3, 2] [11, 10] [2, 1] [0, 0] 1 [] 0
3 [1,0,0,2] [3, 2] [11, 10] [2, 1] [0, 0] 2 [0] 1

Thus, the final answer is [1, 0, 1].

Constraints:

  • 1 <= n == nums.length <= 105
  • 1 <= nums[i] <= 1015
  • 1 <= queries.length <= 105
  • queries[i].length == 3 or 4
    • queries[i] == [1, l, r, k] or,
    • queries[i] == [2, idx, val]
    • 0 <= l <= r <= n - 1
    • 0 <= k <= 5
    • 0 <= idx <= n - 1
    • 1 <= val <= 1015
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 an integer array nums. 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. You are also given a 2D integer array queries, where each queries[i] is either: [1, l, r, k] - Determine the number of indices j such that l <= j <= r and the popcount-depth of nums[j] is equal to k. [2, idx, val] - Update nums[idx] to val. Return an integer array answer, where answer[i] is the number of indices for the ith query of type [1, l, r, k].

Baseline thinking

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

Pattern signal: Array · Segment Tree

Example 1

[2,4]
[[1,0,1,1],[2,1,1],[1,0,1,0]]

Example 2

[3,5,6]
[[1,0,2,2],[2,1,4],[1,1,2,1],[1,0,1,0]]

Example 3

[1,2]
[[1,0,1,1],[2,0,3],[1,0,0,1],[1,0,0,2]]
Step 02

Core Insight

What unlocks the optimal approach

  • Precompute <code>depth[i]</code> for each <code>nums[i]</code> by applying popcount until you reach 1.
  • Maintain six Fenwick trees <code>fenw[0]</code> through <code>fenw[5]</code>, where <code>fenw[d]</code> stores a 1 at index <code>i</code> iff <code>depth[i] == d</code>.
  • For an update <code>[2, idx, val]</code>, remove index idx from its old <code>fenw[old_depth]</code> and insert into <code>fenw[new_depth]</code>; for a query <code>[1, l, r, k]</code>, return <code>fenw[k].query(r) - fenw[k].query(l-1)</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 #3624: Number of Integers With Popcount-Depth Equal to K II
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3624: Number of Integers With Popcount-Depth Equal to K II
// package main
// 
// import "math/bits"
// 
// // https://space.bilibili.com/206214
// type fenwick []int
// 
// func newFenwickTree(n int) fenwick {
// 	return make(fenwick, n+1) // 使用下标 1 到 n
// }
// 
// // a[i] 增加 val
// // 1 <= i <= n
// // 时间复杂度 O(log n)
// func (f fenwick) update(i int, val int) {
// 	for ; i < len(f); i += i & -i {
// 		f[i] += val
// 	}
// }
// 
// // 求前缀和 a[1] + ... + a[i]
// // 1 <= i <= n
// // 时间复杂度 O(log n)
// func (f fenwick) pre(i int) (res int) {
// 	for ; i > 0; i &= i - 1 {
// 		res += f[i]
// 	}
// 	return
// }
// 
// // 求区间和 a[l] + ... + a[r]
// // 1 <= l <= r <= n
// // 时间复杂度 O(log n)
// func (f fenwick) query(l, r int) int {
// 	return f.pre(r) - f.pre(l-1)
// }
// 
// var popDepthList [51]int
// 
// func init() {
// 	for i := 2; i < len(popDepthList); i++ {
// 		popDepthList[i] = popDepthList[bits.OnesCount(uint(i))] + 1
// 	}
// }
// 
// func popDepth(x uint64) int {
// 	if x == 1 {
// 		return 0
// 	}
// 	return popDepthList[bits.OnesCount64(x)] + 1
// }
// 
// func popcountDepth(nums []int64, queries [][]int64) (ans []int) {
// 	n := len(nums)
// 	f := [6]fenwick{}
// 	for i := range f {
// 		f[i] = newFenwickTree(n)
// 	}
// 	update := func(i, delta int) {
// 		d := popDepth(uint64(nums[i]))
// 		f[d].update(i+1, delta)
// 	}
// 
// 	for i := range n {
// 		update(i, 1) // 添加
// 	}
// 
// 	for _, q := range queries {
// 		if q[0] == 1 {
// 			ans = append(ans, f[q[3]].query(int(q[1])+1, int(q[2])+1))
// 		} else {
// 			i := int(q[1])
// 			update(i, -1) // 撤销旧的
// 			nums[i] = q[2]
// 			update(i, 1) // 添加新的
// 		}
// 	}
// 	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 + q log n)
Space
O(n)

Approach Breakdown

BRUTE FORCE
O(n × q) time
O(1) space

For each of q queries, scan the entire range to compute the aggregate (sum, min, max). Each range scan takes up to O(n) for a full-array query. With q queries: O(n × q) total. Point updates are O(1) but queries dominate.

SEGMENT TREE
O(n + q log n) time
O(n) space

Building the tree is O(n). Each query or update traverses O(log n) nodes (tree height). For q queries: O(n + q log n) total. Space is O(4n) ≈ O(n) for the tree array. Lazy propagation adds O(1) per node for deferred updates.

Shortcut: Build O(n), query/update O(log n) each. When you need both range queries AND point updates.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.