2025-08-11 Daily Challenge
Today I have done leetcode's August LeetCoding Challenge with cpp
.
August LeetCoding Challenge 11
Description
Range Product Queries of Powers
Given a positive integer n
, there exists a 0-indexed array called powers
, composed of the minimum number of powers of 2
that sum to n
. The array is sorted in non-decreasing order, and there is only one way to form the array.
You are also given a 0-indexed 2D integer array queries
, where queries[i] = [lefti, righti]
. Each queries[i]
represents a query where you have to find the product of all powers[j]
with lefti <= j <= righti
.
Return an array answers
, equal in length to queries
, where answers[i]
is the answer to the ith
query. Since the answer to the ith
query may be too large, each answers[i]
should be returned modulo 109 + 7
.
Example 1:
Input: n = 15, queries = [[0,1],[2,2],[0,3]] Output: [2,4,64] Explanation: For n = 15, powers = [1,2,4,8]. It can be shown that powers cannot be a smaller size. Answer to 1st query: powers[0] * powers[1] = 1 * 2 = 2. Answer to 2nd query: powers[2] = 4. Answer to 3rd query: powers[0] * powers[1] * powers[2] * powers[3] = 1 * 2 * 4 * 8 = 64. Each answer modulo 109 + 7 yields the same answer, so [2,4,64] is returned.
Example 2:
Input: n = 2, queries = [[0,0]] Output: [2] Explanation: For n = 2, powers = [2]. The answer to the only query is powers[0] = 2. The answer modulo 109 + 7 is the same, so [2] is returned.
Constraints:
1 <= n <= 109
1 <= queries.length <= 105
0 <= starti <= endi < powers.length
Solution
const int MOD = 1e9 + 7;
constexpr int qmul(long long a, long long b, int m) {
return a * b % m;
}
constexpr int qpow(int b, int e, int m) {
int result = 1;
while(e) {
if(e & 1) {
result = qmul(result, b, m);
}
b = qmul(b, b, m);
e >>= 1;
}
return result;
}
constexpr int inv(int a) {
return qpow(a, MOD - 2, MOD);
}
class Solution {
const int MOD = 1e9 + 7;
public:
vector<int> productQueries(int n, vector<vector<int>>& queries) {
vector<int> powers(1);
for(int i = 0; i < 30; ++i) {
if((1 << i) & n) powers.push_back(i);
}
int len = powers.size();
for(int i = 1; i < len; ++i) {
powers[i] += powers[i - 1];
}
int qLen = queries.size();
vector<int> answer(qLen);
for(int i = 0; i < qLen; ++i) {
answer[i] = qpow(2, powers[queries[i][1] + 1] - powers[queries[i][0]], MOD);
}
return answer;
}
};
// Accepted
// 70/70 cases passed (8 ms)
// Your runtime beats 90.43 % of cpp submissions
// Your memory usage beats 89.89 % of cpp submissions (144.9 MB)