AAlgoLoopSpaced repetition for LeetCode
MEDIUMHash Map / SetLeetCode ↗

Count Good Meals

The key idea

A good meal is a pair of dishes whose deliciousness sum is a power of two. Since the maximum sum is bounded (2^21), we can precompute all possible powers of two and use a hash map to count complements efficiently.

Problem

A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two (i.e., 1, 2, 4, 8, ...).

You are given an array deliciousness of integers, where each element represents the deliciousness of a food item. Return the number of different good meals you can make from the array. Since the answer may be large, return it modulo 10^9 + 7.

Two meals are considered different if they use different pairs of indices (order does not matter).

Constraints

Examples

Input: deliciousness = [1,3,5,7,9] Output: 4
Input: deliciousness = [1,1,1,3,3,3,7] Output: 15

Complexity

Time: O(n * log maxSum) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Hash Map / Set problems