Range Product Queries of Powers — LeetCode 2438 Python Solution

MediumBit ManipulationArrayPrefix Sum
Problem
#2438
Pattern
Prefix Sum
Reading time
3 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(m \times \log n), where m is the length of the array \textit{queries}
SpaceO(\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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview