#1711

Count Good Meals

Medium
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages a hash map to count occurrences of each deliciousness value and checks for pairs that sum to powers of two. This reduces the need for nested loops and allows us to find pairs in linear time.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a hash map to count occurrences of each deliciousness value.
  2. 2Step 2: Iterate through the hash map keys and for each key, check all powers of two up to 2^21.
  3. 3Step 3: For each power of two, calculate the complement needed to form that power with the current key.
  4. 4Step 4: If the complement exists in the hash map, calculate the number of good meals based on their counts.
  5. 5Step 5: Return the total count modulo 10^9 + 7.
solution.py18 lines
1# Full working Python code
2
3def count_good_meals(deliciousness):
4    MOD = 10**9 + 7
5    count = 0
6    freq = {}
7    for d in deliciousness:
8        freq[d] = freq.get(d, 0) + 1
9    powers_of_two = [1 << i for i in range(22)]
10    for key in freq:
11        for power in powers_of_two:
12            complement = power - key
13            if complement in freq:
14                if complement == key:
15                    count += (freq[key] * (freq[key] - 1)) // 2
16                else:
17                    count += freq[key] * freq[complement]
18    return count % MOD

Complexity note: The time complexity is O(n) because we iterate through the array once to build the frequency map and then through the map to find pairs, which is efficient. The space complexity is O(n) due to the hash map storing counts of deliciousness values.

  • 1Powers of two can be efficiently checked using bit manipulation.
  • 2Using a hash map allows for quick lookups of counts, reducing time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.