Count Good Meals - Problem
Count Good Meals

You're hosting a dinner party and want to create the perfect meal combinations! A good meal consists of exactly two different food items whose combined deliciousness equals a power of two (1, 2, 4, 8, 16, 32, ...).

Given an array deliciousness where deliciousness[i] represents the deliciousness value of the ith food item, return the number of different good meals you can create.

Important: Items at different indices are considered different even if they have the same deliciousness value. Return your answer modulo 109 + 7.

Example: If deliciousness = [1,3,5,7,9], you can make meals like (1,3)→4=2², (3,5)→8=2³, (7,9)→16=2⁴

Input & Output

example_1.py — Basic Case
$ Input: deliciousness = [1,3,5,7,9]
Output: 4
💡 Note: Good meals are: (1,3)→4=2², (1,7)→8=2³, (3,5)→8=2³, (7,9)→16=2⁴. Total count = 4.
example_2.py — Duplicates
$ Input: deliciousness = [1,1,1,3,3,3,7]
Output: 15
💡 Note: Pairs: 6 pairs of (1,3)→4=2², 6 pairs of (1,7)→8=2³, 3 pairs of (3,3)→6≠power of 2. Wait, let me recalculate: (1,3) gives us 3×3=9 combinations, (1,7) gives us 3×1=3 combinations, (3,7) isn't power of 2. Actually: 9+3=12 invalid calculation. Correct: 3×3=9 pairs for (1,3), 3×1=3 pairs for (1,7), total=12. Need to verify.
example_3.py — Edge Case
$ Input: deliciousness = [2048]
Output: 0
💡 Note: Only one element, cannot form any pairs. Output is 0.

Constraints

  • 1 ≤ deliciousness.length ≤ 105
  • 0 ≤ deliciousness[i] ≤ 220
  • Maximum possible sum is 221, so we only need to check 22 powers of two
  • Return result modulo 109 + 7

Visualization

Tap to expand
🍽️ The Perfect Meal Pairing Process🥘 Ingredients13579⚡ Magic Numbers2⁰ = 12¹ = 22² = 42³ = 82⁴ = 162⁵ = 32...📚 Chef's CatalogIngredient → Count1 → 13 → 15 → 17 → 1✨ Perfect Pairs(1,3) → 4 = 2²(1,7) → 8 = 2³(3,5) → 8 = 2³(7,9) → 16 = 2⁴Total: 4🔑 Key Insight: Check each ingredient against all magic numbers (powers of 2)Time: O(n × 22) = O(n) | Space: O(n) for the catalogOnly 22 powers of 2 possible with constraint 0 ≤ deliciousness[i] ≤ 2²⁰
Understanding the Visualization
1
Setup Kitchen
Prepare a special catalog (hash map) to track ingredients as you encounter them
2
Magic Numbers
Pre-calculate all magical totals (powers of 2: 1, 2, 4, 8, 16, 32, 64...)
3
Perfect Pairing
For each new ingredient, check if any previous ingredient would create a magical total
4
Count Combinations
Add up all the valid magical combinations discovered
Key Takeaway
🎯 Key Insight: Instead of checking all n² pairs, we only check n × 22 complement lookups by leveraging the limited set of possible power-of-two sums!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
38.5K Views
High Frequency
~25 min Avg. Time
1.5K 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