πΉ Problem: Product Queries of Powers of Two
Difficulty: #Medium
Tags: #BitManipulation #PrefixProduct #ModularArithmetic
π Problem Summary
We are given:
- An integer
n
which can be expressed as a sum of distinct powers of two (from its binary representation). - Several queries, each
[l, r]
, representing indices in the sorted list of powers-of-two fromn
.
For each query, compute the product of powers-of-two in that index range, modulo 10^9 + 7
.
π§ My Thought Process
-
Step 1: Understanding the data structure
Every
n
can be broken into its binary representation, where each1
corresponds to a power of two that makes upn
. Example:
n = 10 (binary 1010) β powers = [2, 8]
-
Brute Force Idea:
For each query, loop through the subarraypowers[l:r]
and multiply the elements, taking modulo each time.
This works because:- The number of powers is at most 32 (since n β€ 10^9).
- The queries are applied on a very small list.
Optimized Strategy (not implemented here, but possible):
Precompute prefix products modulo MOD so that each query can be answered in O(1) time instead of O(length of range).
Formula:
product(l, r) = prefix[r] * inverse(prefix[l-1]) % MOD
where inverse
is computed using modular exponentiation.
- Algorithm Used: Bit manipulation to extract powers of two + modular multiplication.
βοΈ Code Implementation (Python)
class Solution:
def productQueries(self, n: int, queries: List[List[int]]) -> List[int]:
MOD = 10**9 + 7
powers = []
i = 0
# Extract powers of two from n's binary representation
while (1 << i) <= n:
if n & (1 << i):
powers.append(1 << i)
i += 1
results = []
for l, r in queries:
product = 1
for j in range(l, r + 1):
product *= powers[j]
product %= MOD
results.append(product)
return results
β±οΈ Time & Space Complexity
-
Time: O(Q Γ K)
- Q = number of queries
- K = length of the queried subarray (at most number of set bits in n β€ 32) β Effectively O(Q) in practice.
Space: O(K) to store the powers.
π§© Key Takeaways
- β Using binary representation is a clean way to extract powers-of-two from an integer.
- π‘ Because the list of powers is tiny (β€ 32), even a brute-force query loop is fast enough.
- π For larger constraints, prefix products + modular inverses are the way to go.
π Reflection (Self-Check)
- [x] Could I solve this without help?
- [x] Did I write code from scratch?
- [x] Did I understand why it works?
- [x] Will I be able to recall this in a week?
π Progress Tracker
Metric | Value |
---|---|
Day | 57 |
Total Problems Solved | 412 |
Confidence Today | π |
Leetcode Rating | 1572 |
Top comments (0)