#1969

Minimum Non-Zero Product of the Array Elements

Medium
MathGreedyRecursionBit ManipulationMathematical Properties
LeetCode ↗

Approaches

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

Intuition

Time O(log n)Space O(1)

The optimal solution leverages the properties of binary numbers and the fact that we can swap bits to minimize the product. By focusing on the highest bit positions and ensuring we keep the largest numbers intact, we can achieve the minimum non-zero product efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the maximum number in nums, which is 2^p - 1.
  2. 2Step 2: The minimum non-zero product can be derived from the formula: ((2^p - 2)^(2^(p-1) - 1) * (2^p - 1)) % (10^9 + 7).
  3. 3Step 3: Return the result.
solution.py8 lines
1# Full working Python code
2
3def minNonZeroProduct(p):
4    mod = 10**9 + 7
5    max_num = (1 << p) - 1
6    return (pow(max_num - 1, (1 << (p - 1)) - 1, mod) * max_num) % mod
7
8print(minNonZeroProduct(3))  # Example call

Complexity note: The time complexity is O(log n) due to the fast exponentiation method used to compute powers. The space complexity is O(1) since we are using a constant amount of space.

  • 1Swapping bits can help minimize products.
  • 2Understanding binary representation is crucial.

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