Magicsheet logo

Range Product Queries of Powers

Medium
47.2%
Updated 6/1/2025

Range Product Queries of Powers

What is this problem about?

The Range Product Queries of Powers problem gives you a number n and queries [l, r]. First, extract all powers of 2 in n's binary representation (like 2^0, 2^1, 2^3 for n=11=1011). For each query [l, r], return the product of powers at positions l through r, modulo 10^9+7. This coding problem uses prefix products on the bit decomposition. The array, bit manipulation, and prefix sum interview pattern is demonstrated.

Why is this asked in interviews?

Goldman Sachs, Amazon, and Bloomberg ask this to test bit decomposition with prefix products — combining bit manipulation knowledge with prefix sum design. It validates understanding of extracting power-of-2 components from a number.

Algorithmic pattern used

Bit extraction + prefix product array. Extract all set bits of n in ascending order: powers = [i for i in range(30) if n >> i & 1]. Build prefix product: prefix[i] = product(2^powers[0..i-1]). For query [l, r]: answer = prefix[r+1] / prefix[l] (mod p) = prefix[r+1] * modInverse(prefix[l]).

Or simpler: just compute product(powers[l..r]) = multiply (1 << powers[i]) for i in [l, r].

Example explanation

n=15 (1111). powers=[0,1,2,3] (bits 0,1,2,3 set). Values=[1,2,4,8]. Query [1,3]: product=2×4×8=64 mod 10^9+7. Query [0,2]: product=1×2×4=8.

Common mistakes candidates make

  • Not extracting powers in sorted order (must be ascending).
  • Using modular division without modular inverse (must use Fermat's little theorem).
  • Off-by-one in query bounds.
  • Confusing power index (bit position) with power value (2^bit).

Interview preparation tip

Range Product Queries tests prefix products with modular arithmetic. Modular division requires a * pow(b, MOD-2, MOD) (Fermat's little theorem when MOD is prime). Practice bit decomposition: "extract all set bits," "decompose n into power-of-2 components." Combine with prefix products for efficient range queries.

Similar Questions