#3624

Number of Integers With Popcount-Depth Equal to K II

Hard
ArrayDivide and ConquerBinary Indexed TreeSegment TreeHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + q log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n + q log n)Space O(n)

Precompute the popcount-depth for all numbers and use Fenwick trees to efficiently answer range queries.

⚙️

Algorithm

3 steps
  1. 1Step 1: Precompute the popcount-depth for each element in nums and store counts in Fenwick trees for depths 0 to 5.
  2. 2Step 2: For each query of type [1, l, r, k], use the Fenwick tree to get the count of indices with depth k in the range [l, r].
  3. 3Step 3: For updates, adjust the Fenwick tree based on the new depth of the updated number.
solution.py8 lines
1def popcount(n): return bin(n).count('1')
2def popcount_depth(x): d = 0; while x > 1: x = popcount(x); d += 1; return d
3class FenwickTree: def __init__(self, size): self.size = size; self.tree = [0] * (size + 1)
4 def update(self, idx, delta): while idx <= self.size: self.tree[idx] += delta; idx += idx & -idx
5 def query(self, idx): total = 0; while idx > 0: total += self.tree[idx]; idx -= idx & -idx; return total
6 def range_query(self, left, right): return self.query(right) - self.query(left - 1)
7def process_queries(nums, queries): n = len(nums); depths = [popcount_depth(num) for num in nums]; fenwick = [FenwickTree(n) for _ in range(6)]; for i in range(n): fenwick[depths[i]].update(i + 1, 1); results = []
8 for query in queries: if query[0] == 1: results.append(fenwick[query[3]].range_query(query[1] + 1, query[2] + 1)); else: old_depth = depths[query[1]]; new_depth = popcount_depth(query[2]); depths[query[1]] = new_depth; fenwick[old_depth].update(query[1] + 1, -1); fenwick[new_depth].update(query[1] + 1, 1); return results

Complexity note: Precomputation takes O(n), each query takes O(log n) for Fenwick tree operations.

  • 1Precomputing values can save time during queries.
  • 2Using data structures like Fenwick trees allows efficient range queries.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.