#2438

Range Product Queries of Powers

Medium
ArrayBit ManipulationPrefix SumPrefix SumModular Arithmetic
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + q)
Space
O(1)
O(n)
💡

Intuition

Time O(n + q)Space O(n)

The optimal approach leverages prefix products to compute the product of any subarray in constant time after an initial setup. This reduces the time complexity significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create the powers array from the binary representation of n.
  2. 2Step 2: Build a prefix product array where each entry at index i contains the product of all elements in powers up to index i.
  3. 3Step 3: For each query, compute the product using the prefix product array to get the result in constant time.
solution.py10 lines
1def rangeProductQueries(n, queries):
2    powers = [1 << i for i in range(n.bit_length()) if (n & (1 << i))]
3    prefix_products = [1] * (len(powers) + 1)
4    for i in range(1, len(powers) + 1):
5        prefix_products[i] = (prefix_products[i - 1] * powers[i - 1]) % (10**9 + 7)
6    answers = []
7    for left, right in queries:
8        product = (prefix_products[right + 1] * pow(prefix_products[left], -1, 10**9 + 7)) % (10**9 + 7)
9        answers.append(product)
10    return answers

Complexity note: The time complexity is O(n + q) because we spend O(n) to create the powers and prefix products, and O(q) to answer each query in constant time.

  • 1Understanding binary representation helps in forming the powers array efficiently.
  • 2Using prefix products allows for quick calculations of subarray products.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.