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: [1024]
💡 Note: 31 = 16+8+4+2+1, so powers = [1,2,4,8,16]. Query [0,4]: 1×2×4×8×16=1024.

Constraints

  • 1 ≤ n ≤ 109
  • 1 ≤ queries.length ≤ 105
  • 0 ≤ lefti ≤ righti < popcount(n)

Visualization

Tap to expand
Range Product Queries of Powers INPUT n = 15 (binary: 1111) 15 = 8 + 4 + 2 + 1 15 = 2³ + 2² + 2¹ + 2⁰ powers[] array: 1 idx 0 2 idx 1 4 idx 2 8 idx 3 2⁰ Queries: Query 1: [0, 1] Query 2: [2, 2] MOD = 10^9 + 7 ALGORITHM STEPS 1 Build powers[] Extract set bits from n Sort in ascending order 2 Process Query 1 [0,1]: powers[0]*powers[1] = 1 * 2 = 2 1 2 4 8 3 Process Query 2 [2,2]: powers[2] = 4 1 2 4 8 4 Apply Modulo Result % (10^9 + 7) for large products Time: O(queries * log n) FINAL RESULT Query 1: [0, 1] Range: index 0 to 1 Product: 1 x 2 = 2 2 Query 2: [2, 2] Range: index 2 only Product: 4 4 Output Array: [2, 4] OK - Verified! Key Insight: The powers[] array contains powers of 2 from n's binary representation, sorted ascending. Product of powers of 2 equals 2^(sum of exponents). For range [L,R], multiply all powers[i] where L <= i <= R. Use prefix exponent sums for O(1) query optimization with large inputs. TutorialsPoint - Range Product Queries of Powers | Optimal Solution
Asked in
Google 12 Microsoft 8 Amazon 6
15.3K Views
Medium Frequency
~25 min Avg. Time
487 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen