Range Product Queries of Powers - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
n = 15, queries = [[0,1],[2,2]]
›
Output:
[2,4]
💡 Note:
15 = 8+4+2+1, so powers = [1,2,4,8]. Query [0,1]: 1×2=2. Query [2,2]: 4.
Example 2 — Single Element
$
Input:
n = 2, queries = [[0,0]]
›
Output:
[2]
💡 Note:
2 = 2¹, so powers = [2]. Query [0,0]: 2.
Example 3 — Large Range
$
Input:
n = 31, queries = [[0,4]]
›
Output:
[248]
💡 Note:
31 = 16+8+4+2+1, so powers = [1,2,4,8,16]. Query [0,4]: 1×2×4×8×16=1024, but 1024 mod (10⁹+7) = 1024.
Constraints
- 1 ≤ n ≤ 109
- 1 ≤ queries.length ≤ 105
- 0 ≤ lefti ≤ righti < popcount(n)
Visualization
Tap to expand
Understanding the Visualization
1
Input
n = 15, queries = [[0,1],[2,2]]
2
Process
Convert to powers array [1,2,4,8] and calculate range products
3
Output
Return [2,4] with modulo applied
Key Takeaway
🎯 Key Insight: Convert products to sums of exponents, then use prefix sums for O(1) range queries
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code