Count Good Meals LeetCode solution in Python

1
class Solution:
2
def countPairs(self, deliciousness: List[int]) -> int:
3
pows = [2**i for i in range(0, 22)] # form our list of powers of 2
4
dp_seen = (
5
{}
6
) # dict to store what we've seen - dynamic programming solution for time requirement
7
count = 0 # to store the answer
8

9
for j in range(0, len(deliciousness)):
10
for i in range(0, len(pows)):
11
if (
12
pows[i] - deliciousness[j] in dp_seen
13
): # "if we find a previous deliciousness[j] as pows[i] - deliciousness[j], then we will add dp_seen[deliciousness[j]] to count"
14
count += dp_seen[pows[i] - deliciousness[j]]
15
if deliciousness[j] in dp_seen:
16
dp_seen[deliciousness[j]] += 1
17
else:
18
dp_seen[deliciousness[j]] = 1
19

20
return count % (
21
10**9 + 7
22
) # the arbitrary modulo, presumably to reduce the answer size

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0