2438. Range Product Queries of Powers #2039
-
Topics: Given a positive integer You are also given a 0-indexed 2D integer array Return an array Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to efficiently answer multiple range product queries on an array derived from the binary representation of a given positive integer Approach
Let's implement this solution in PHP: 2438. Range Product Queries of Powers <?php
/**
* @param Integer $n
* @param Integer[][] $queries
* @return Integer[]
*/
function productQueries($n, $queries) {
$mod = 1000000007;
$powers = [];
$current = 1;
$temp = $n;
while ($temp) {
if ($temp & 1) {
$powers[] = $current;
}
$temp = $temp >> 1;
$current *= 2;
}
$ans = [];
foreach ($queries as $q) {
$l = $q[0];
$r = $q[1];
$product = 1;
for ($i = $l; $i <= $r; $i++) {
$product = ($product * $powers[$i]) % $mod;
}
$ans[] = $product;
}
return $ans;
}
// Test cases
$n = 15;
$queries = [[0,1],[2,2],[0,3]];
print_r(productQueries($n, $queries)); // Output: [2, 4, 64]
$n = 2;
$queries = [[0,0]];
print_r(productQueries($n, $queries)); // Output: [2]
?> Explanation:
This approach efficiently handles the constraints by leveraging the binary decomposition of |
Beta Was this translation helpful? Give feedback.
We need to efficiently answer multiple range product queries on an array derived from the binary representation of a given positive integer
n
. The array consists of the minimum number of distinct powers of 2 that sum ton
, sorted in non-decreasing order. Each query requires computing the product of elements within a specified range in this array, modulo 109 + 7.Approach
Generate Powers Array:
n
into its binary representation. Each set bit in the binary form ofn
corresponds to a power of 2. For example, ifn
is 15 (binary1111
), the powers array will be[1, 2, 4, 8]
.n
from the least significant bit (LSB) to…