This problem can be solved in several ways. We will discuss the author’s solution here.
For each from to , we will generate how many ways we can take an array of size such that the elements are between and and the bitwise-and value of the array is .
DP approach: (TLE expected)
Let be the number of ways we can generate an array of size such that the bitwise-and of the array is , now the transition will look like
here is an integer between and and is an integer between and , and this represents a new element being added to an array of size that previously had bitwise-and value of .
Notice that the number of ways can be big that it won’t fit in normal bits integers, we will need structures that can work with larger numbers(BigInt). But there’s an issue Let’s say we are working with an array of size , then the number of ways can contain ~ digits. as can be up to , we can’t store numbers with this many digits.
Observation: For a particular value of and , let’s the answer for length be , then for all , and will be the bitwise-and value of all integers between and . Now it can be proven that for all , will be the same as as once reaches that number it won’t change. Turns out that in the given constraints reaches that minimum value within ~ length. So, if a query is given with , we can just output that minimum value without any calculations. Otherwise, we can run the DP to generate the result.
The complexity of this approach will be , here is the time taken for BigInt operations. This will be too slow to pass.
Convolution approach:
Notice that the transition explained in the DP approach is just and-Convolution. Let’s have a polynomial of degree where for , 0 otherwise. Now, and-Convolution of with itself times will essentially give us , now represents the number of ways we can generate an array of size such that the bitwise-and of the array is and that is what we are after. Do and-Convolution using Fast Walsh Hadamard Transforms and you will have a fast solution. Do the BigInt multiplications in FWHT using Fast Fourier transform and you have a faster solution.
Time Complexity:
Space Complexity:
Bonus Problem:
Given the upper limit of , can you find out what value of , will take the longest array to reach ?