#3145
Find Products of Elements of Big Array
HardArrayBinary SearchBit ManipulationBit ManipulationDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(q * log(n)) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(q * log(n))Space O(1)
The optimal approach leverages the properties of binary representation and bit manipulation to directly compute the product of the powerful array elements without generating the entire array. This allows us to handle large indices efficiently.
⚙️
Algorithm
3 steps- 1Step 1: For each query, calculate the product of the powerful array elements from 'from' to 'to' using bit manipulation.
- 2Step 2: Use a helper function to determine the contribution of each bit position for the numbers in the range.
- 3Step 3: Compute the product modulo the specified value.
solution.py18 lines
1# Full working Python code
2
3def count_powers(n, bit):
4 count = 0
5 for i in range(n + 1):
6 if (i & (1 << bit)):
7 count += 1
8 return count
9
10def find_products(queries):
11 results = []
12 for from_i, to_i, mod_i in queries:
13 product = 1
14 for bit in range(32):
15 count = count_powers(to_i, bit) - count_powers(from_i - 1, bit)
16 product = (product * pow(2, count, mod_i)) % mod_i
17 results.append(product)
18 return resultsℹ
Complexity note: The time complexity is O(q * log(n)) because for each query, we compute the contribution of each bit position, which requires logarithmic time relative to the maximum number in the query.
- 1Understanding binary representation is crucial for efficiently computing powers of two.
- 2Using bit manipulation can drastically reduce the time complexity of the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.