Skip to content

1969. Minimum Non-Zero Product of the Array Elements 👎

  • Time: $O(\log p)$
  • Space: C++/Java: $O(\log p)$, Python: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int minNonZeroProduct(int p) {
    // Can always turn [1..2^p - 1] to [1, 1, ..., 2^p - 2, 2^p - 2, 2^p - 1].
    const long n = 1L << p;
    const long halfCount = n / 2 - 1;
    return modPow(n - 2, halfCount) * ((n - 1) % kMod) % kMod;
  }

 private:
  static constexpr int kMod = 1'000'000'007;

  long modPow(long x, long n) {
    if (n == 0)
      return 1L;
    x %= kMod;
    if (n % 2 == 1)
      return x * modPow(x, n - 1) % kMod;
    return modPow(x * x, n / 2) % kMod;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int minNonZeroProduct(int p) {
    // Can always turn [1..2^p - 1] to [1, 1, ..., 2^p - 2, 2^p - 2, 2^p - 1].
    final long n = 1L << p;
    final long halfCount = n / 2 - 1;
    return (int) (modPow(n - 2, halfCount) * ((n - 1) % kMod) % kMod);
  }

  private static final int kMod = 1_000_000_007;

  private long modPow(long x, long n) {
    if (n == 0)
      return 1L;
    x %= kMod;
    if (n % 2 == 1)
      return x * modPow(x, n - 1) % kMod;
    return modPow(x * x, n / 2) % kMod;
  }
}
1
2
3
4
5
6
7
class Solution:
  def minNonZeroProduct(self, p: int) -> int:
    kMod = 1_000_000_007
    # Can always turn [1..2^p - 1] to [1, 1, ..., 2^p - 2, 2^p - 2, 2^p - 1].
    n = 1 << p
    halfCount = n // 2 - 1
    return pow(n - 2, halfCount, kMod) * ((n - 1) % kMod) % kMod