From 8d99adb55640f586c11c0f2135b1801f0a68efd5 Mon Sep 17 00:00:00 2001 From: NEHA-AMIN Date: Tue, 12 Aug 2025 02:46:52 +0530 Subject: [PATCH] Solution of Product Queries --- .../productQueries.cpp | 0 .../productQueries.java | 44 +++++++++++++++++++ .../productQueries.py | 30 +++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 Arrays & Strings/#2438 - Range Product Queries of Powers- Medium/productQueries.cpp create mode 100644 Arrays & Strings/#2438 - Range Product Queries of Powers- Medium/productQueries.java create mode 100644 Arrays & Strings/#2438 - Range Product Queries of Powers- Medium/productQueries.py diff --git a/Arrays & Strings/#2438 - Range Product Queries of Powers- Medium/productQueries.cpp b/Arrays & Strings/#2438 - Range Product Queries of Powers- Medium/productQueries.cpp new file mode 100644 index 0000000..e69de29 diff --git a/Arrays & Strings/#2438 - Range Product Queries of Powers- Medium/productQueries.java b/Arrays & Strings/#2438 - Range Product Queries of Powers- Medium/productQueries.java new file mode 100644 index 0000000..7259bea --- /dev/null +++ b/Arrays & Strings/#2438 - Range Product Queries of Powers- Medium/productQueries.java @@ -0,0 +1,44 @@ +import java.util.*; + +class Solution { + private final int mod = (int)1e9 + 7; + + public int[] productQueries(int n, int[][] queries) { + List p2 = new ArrayList<>(); + List 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 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; + } +} diff --git a/Arrays & Strings/#2438 - Range Product Queries of Powers- Medium/productQueries.py b/Arrays & Strings/#2438 - Range Product Queries of Powers- Medium/productQueries.py new file mode 100644 index 0000000..6e4a4b1 --- /dev/null +++ b/Arrays & Strings/#2438 - Range Product Queries of Powers- Medium/productQueries.py @@ -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