Skip to content

Commit 73d2fdf

Browse files
authored
Create minimum-non-zero-product-of-the-array-elements.py
1 parent 440e2f6 commit 73d2fdf

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Time: O(min(p, logM))
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def minNonZeroProduct(self, p):
6+
"""
7+
:type p: int
8+
:rtype: int
9+
"""
10+
MOD = 10**9+7
11+
12+
# max_num = 2^p-1
13+
max_num_mod = (pow(2, p, MOD)-1)%MOD # max_num % MOD
14+
15+
# pair_product = max_num-1
16+
pair_product_mod = (max_num_mod-1)%MOD # (max_num_mod-1) % MOD
17+
18+
# since pair_product^MOD % MOD = pair_product_mod^MOD % MOD = pair_product_mod
19+
# => pair_product_mod^(MOD-1) % MOD = 1
20+
# => pair_product_mod^(pair_cnt) % MOD = pair_product_mod^(pair_cnt%(MOD-1)) %MOD
21+
pair_cnt_mod_m_1 = (pow(2, p-1, MOD-1)-1) % (MOD-1) # pair_cnt%(MOD-1)
22+
23+
# the ans is:
24+
# max_num * pair_product^pair_cnt % MOD
25+
# = max_num_mod * pair_product_mod^(pair_cnt_mod_m_1) % MOD
26+
return (max_num_mod*pow(pair_product_mod, pair_cnt_mod_m_1, MOD)) % MOD

0 commit comments

Comments
 (0)