- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- Apply updates and combine the affected nodes to answer each query.
Code notes
- 70 lines of Python from the credited upstream file number-of-integers-with-popcount-depth-equal-to-k-ii.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the build once, then multiply the logarithmic update or query path by the number of operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234 56def popcount(x):7 return bin(x).count('1')8 9 10def ceil_log2(x):11 return (x-1).bit_length()12 13 14class BIT(object): 15 def __init__(self, n):16 self.__bit = [0]*(n+1) 17 18 def add(self, i, val):19 i += 1 20 while i < len(self.__bit):21 self.__bit[i] += val22 i += (i & -i)23 24 def query(self, i):25 i += 1 26 ret = 027 while i > 0:28 ret += self.__bit[i]29 i -= (i & -i)30 return ret31 32 33MAX_N = 10**1534MAX_BIT_LEN = MAX_N.bit_length()35D = [0]*(MAX_BIT_LEN+1)36for i in xrange(2, MAX_BIT_LEN+1):37 D[i] = D[popcount(i)]+138MAX_K = 039while MAX_N != 1: 40 MAX_N = ceil_log2(MAX_N)41 MAX_K += 142class Solution(object):43 def popcountDepth(self, nums, queries):44 """45 :type nums: List[int]46 :type queries: List[List[int]]47 :rtype: List[int]48 """49 def count(x):50 return D[popcount(x)]+1 if x != 1 else 051 52 bit = [BIT(len(nums)) for _ in xrange(MAX_K+1)]53 for i in xrange(len(nums)):54 bit[count(nums[i])].add(i, +1)55 result = []56 for q in queries:57 if q[0] == 1:58 _, l, r, k = q59 assert(k < len(bit))60 result.append(bit[k].query(r)-bit[k].query(l-1))61 else:62 _, i, x = q63 old_d = count(nums[i])64 new_d = count(x)65 if new_d != old_d:66 bit[old_d].add(i, -1)67 bit[new_d].add(i, +1)68 nums[i] = x69 return result70