Count Good Meals - 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.

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: Items with different indices are considered different even if they have the same deliciousness value.

Input & Output

Example 1 — Basic Case
$ Input: deliciousness = [1,3,5,7,9]
Output: 4
💡 Note: Good meals are: (1,3)→4, (1,7)→8, (3,5)→8, (7,9)→16. All sums are powers of 2.
Example 2 — Duplicates
$ Input: deliciousness = [1,1,1,3,3,3,7]
Output: 12
💡 Note: Multiple pairs can form same sum: 1+3=4 (9 combinations), 1+7=8 (3 combinations). Total: 9+3=12.
Example 3 — No Valid Pairs
$ Input: deliciousness = [2,5,11]
Output: 1
💡 Note: Check all pairs: 2+5=7 (not power of 2), 2+11=13 (not power of 2), 5+11=16 (power of 2). So result is 1.

Constraints

  • 1 ≤ deliciousness.length ≤ 2 × 104
  • 0 ≤ deliciousness[i] ≤ 220

Visualization

Tap to expand
Count Good Meals - Hash Map Optimization INPUT deliciousness array: 1 i=0 3 i=1 5 i=2 7 i=3 9 i=4 Powers of 2: 2, 4, 8, 16, 32, ... Good Meal: Two items where sum = power of 2 Valid Pairs: 1+3=4, 1+7=8 3+5=8, 7+9=16 1+15=16 (if exists) ALGORITHM STEPS 1 Initialize Hash Map Track seen values + counts 2 For each food item Iterate through array 3 Check all 2^k targets Find complement in map 4 Add current to map Update count, return total Hash Map Process: val=1: check 2^k-1 in map val=3: 4-3=1 exists! +1 val=5: 8-5=3 exists! +1 val=7: 8-7=1 exists! +1 val=9: 16-9=7 exists! +1 Total count = 4 FINAL RESULT Output: 4 OK - Verified 4 Good Meals Found: 1 + 3 = 4 4 = 2^2 1 + 7 = 8 8 = 2^3 3 + 5 = 8 8 = 2^3 7 + 9 = 16 16 = 2^4 Key Insight: Use a hash map to store seen values. For each new value, check if (2^k - value) exists in the map for all relevant powers of 2. This reduces O(n^2) brute force to O(n * log(maxSum)) time complexity. Max sum is 2*10^20, so we only need to check ~22 powers of 2 per element. TutorialsPoint - Count Good Meals | Hash Map Optimization
Asked in
Facebook 35 Google 28 Amazon 22
28.0K Views
Medium Frequency
~25 min Avg. Time
895 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen