Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import java.util.*;

class Solution {
private final int mod = (int)1e9 + 7;

public int[] productQueries(int n, int[][] queries) {
List<Integer> p2 = new ArrayList<>();
List<Integer> res = new ArrayList<>();
int i = 0, k = 0;

while (n > 0) {
if ((n & 1) == 1) {
p2.add(i);
if (k > 0) {
p2.set(k, p2.get(k) + p2.get(k - 1)); // prefix sum of exponents
}
k++;
}
n >>= 1;
i++;
}

for (int[] q : queries) {
int p = p2.get(q[1]) - (q[0] > 0 ? p2.get(q[0] - 1) : 0);
res.add(fastPow(2, p));
}

// Convert List<Integer> to int[]
return res.stream().mapToInt(Integer::intValue).toArray();
}

private int fastPow(int base, int exp) {
long result = 1;
long b = base;
while (exp > 0) {
if ((exp & 1) == 1) {
result = (result * b) % mod;
}
b = (b * b) % mod;
exp >>= 1;
}
return (int) result;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Solution:
MOD = 10**9 + 7

def productQueries(self, n: int, queries: list[list[int]]) -> list[int]:
p2 = []
i = k = 0

while n:
if n & 1:
p2.append(i)
if k > 0:
p2[k] += p2[k - 1] # prefix sum of exponents
k += 1
n >>= 1
i += 1

res = []
for q in queries:
p = p2[q[1]] - (p2[q[0] - 1] if q[0] > 0 else 0)
res.append(self.fastPow(2, p))
return res

def fastPow(self, base: int, exp: int) -> int:
result = 1
while exp:
if exp & 1:
result = (result * base) % self.MOD
base = (base * base) % self.MOD
exp >>= 1
return result