Range Product Queries of Powers - Problem
Range Product Queries of Powers
Imagine you have a positive integer
Given this breakdown, you create an array called
Now comes the interesting part! You're given multiple range queries, where each query asks: "What's the product of all powers from index left to index right?"
Since these products can become extremely large, return each answer modulo
Goal: Efficiently compute range products of powers of 2 that sum to n.
Input: A positive integer n and an array of range queries.
Output: An array of products for each query, modulo 10⁹ + 7.
Imagine you have a positive integer
n and need to break it down into its binary representation using powers of 2. For example, if n = 13, then 13 = 8 + 4 + 1 = 2³ + 2² + 2⁰.Given this breakdown, you create an array called
powers containing these powers of 2 in non-decreasing order. For n = 13, the array would be [1, 4, 8] (representing [2⁰, 2², 2³]).Now comes the interesting part! You're given multiple range queries, where each query asks: "What's the product of all powers from index left to index right?"
Since these products can become extremely large, return each answer modulo
10⁹ + 7.Goal: Efficiently compute range products of powers of 2 that sum to n.
Input: A positive integer n and an array of range queries.
Output: An array of products for each query, modulo 10⁹ + 7.
Input & Output
example_1.py — Basic Case
$
Input:
n = 13, queries = [[0,2], [1,2]]
›
Output:
[32, 32]
💡 Note:
n = 13 = 1 + 4 + 8 (binary: 1101), so powers = [1,4,8]. Query [0,2]: 1×4×8 = 32. Query [1,2]: 4×8 = 32.
example_2.py — Single Element
$
Input:
n = 8, queries = [[0,0]]
›
Output:
[8]
💡 Note:
n = 8 = 2³, so powers = [8]. Query [0,0] returns powers[0] = 8.
example_3.py — Large Powers
$
Input:
n = 15, queries = [[0,1], [2,3]]
›
Output:
[4, 32]
💡 Note:
n = 15 = 1 + 2 + 4 + 8, so powers = [1,2,4,8]. Query [0,1]: 1×2 = 2. Query [2,3]: 4×8 = 32.
Constraints
- 1 ≤ n ≤ 109
- 1 ≤ queries.length ≤ 105
- 0 ≤ lefti ≤ righti < powers.length
- powers.length ≤ 30 (since n ≤ 109 < 230)
Visualization
Tap to expand
Understanding the Visualization
1
Binary Decomposition
Convert n to its binary representation to find required powers of 2
2
Build Powers Array
Create sorted array of powers: [2^0, 2^2, 2^3, ...] for set bits
3
Optimize with Prefix Products
Precompute cumulative products to answer any range query in O(1)
4
Handle Large Numbers
Apply modular arithmetic throughout to keep numbers manageable
Key Takeaway
🎯 Key Insight: By preprocessing powers and prefix products, we transform an O(q × log n) problem into O(log n + q), making it optimal for multiple queries on the same powers array.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code