Problem Description
Given an integer array "deliciousness" where each element represents the deliciousness value of a food item, count the number of good meals you can make. A good meal is defined as a combination of two distinct items such that their sum is a power of 2. Return the final count modulo 10^9 + 7.
Key Insights
- A good meal is formed by two items whose sum equals 2^k for some k; precompute possible power of two values in the valid range.
- Use a hash table to keep track of frequencies of already seen deliciousness values.
- For each new food item, compute the required complement for each power of two and check if it exists in the hash table.
- The order of selection matters only by index, and duplicate values are allowed if indices differ.
Space and Time Complexity
Time Complexity: O(n * log(maxSum)) where n is the number of food items and log(maxSum) is the number of powers of two considered (constant in this context). Space Complexity: O(n) for the hash table (or frequency counter).
Solution
The approach uses a hash map (or dictionary) to maintain the count of previously seen deliciousness values. For each current value, the algorithm iterates through potential power-of-two sums and calculates the required complement (complement = power - current value). If the complement exists in the hash map, it adds the corresponding frequency to the overall count of good meals. Finally, update the hash table with the current value frequency. The modulo operation is applied to prevent overflow. This method avoids a double loop by leveraging the constant number of power values possible (given the constraints).