Range Product Queries of Powers — LeetCode 2438 Python Solution
- Problem
- #2438
- Pattern
- Prefix Sum
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- 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.
Python solution
class Solution:
def productQueries(self, n: int, queries: List[List[int]]) -> List[int]:
powers = []
while n:
x = n & -n
powers.append(x)
n -= x
mod = 10**9 + 7
ans = []
for l, r in queries:
x = 1
for i in range(l, r + 1):
x = x * powers[i] % mod
ans.append(x)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times \log n), where m is the length of the array \textit{queries} |
| Space | O(\log n) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 2438. Range Product Queries of Powers is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2438. Range Product Queries of Powers?
- LeetCode 2438. Range Product Queries of Powers is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2438. Range Product Queries of Powers?
- The Python solution on this page runs in O(m \times \log n), where m is the length of the array \textit{queries}.
- What is the space complexity of LeetCode 2438. Range Product Queries of Powers?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 2438. Range Product Queries of Powers cover?
- LeetCode 2438. Range Product Queries of Powers is tagged Bit Manipulation, Array and Prefix Sum on LeetCode.