Count Good Meals Problem
Description
LeetCode Problem 1711.
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 10^9 + 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 <= 10^50 <= deliciousness[i] <= 2^20
Solution
Approach: Hash Table + Powers of Two
Checking every pair is O(n^2), which is too slow. Instead, note that a sum can only be one of a few powers of two.
Walk through the array, keeping a hash table cnt of how many times each value appeared so far. For the current value d, try every power of two s up to twice the largest value, and add cnt[s - d] to the answer: those are the earlier items that pair with d. Then increase cnt[d]. Take the answer modulo 10^9 + 7.
Complexity: O(n log M) time and O(n) space, where n is the length of deliciousness and M is the largest value (here at most 2^20).
from collections import Counter
class Solution:
def countPairs(self, deliciousness: List[int]) -> int:
mod = 10**9 + 7
mx = max(deliciousness) << 1
cnt = Counter()
ans = 0
for d in deliciousness:
s = 1
while s <= mx:
ans = (ans + cnt[s - d]) % mod
s <<= 1
cnt[d] += 1
return ans