Leetcode - Count Good Meals Solution
1 min read

Leetcode - Count Good Meals Solution

A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two.

You can pick any two different foods to make a good meal.

Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i​​​​​​th​​​​​​​​ item of food, return the number of different good meals you can make from this list modulo 109 + 7.

Note that items with different indices are considered different even if they have the same deliciousness value.

Example 1:

Input: deliciousness = [1,3,5,7,9]
Output: 4
Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9).
Their respective sums are 4, 8, 8, and 16, all of which are powers of 2.

Example 2:

Input: deliciousness = [1,1,1,3,3,3,7]
Output: 15
Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.

Constraints:

• 1 <= deliciousness.length <= 105
• 0 <= deliciousness[i] <= 220

Solution in Python

class Solution:
def countPairs(self, deliciousness: List[int]) -> int:
def sumOfAP(n):
return n*(n-1)//2
c = Counter(deliciousness)
powerOfTwos = {2**i for i in range(22)}
possibilities = 0
for x in c.keys():
if x*2 in powerOfTwos :
possibilities += sumOfAP(c[x])
for i in powerOfTwos:
y = i - x
if y != x and y>-1:
possibilities += c[x]*c[y]
c[x] = 0
return possibilities%(10**9 + 7)

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×