Count Good Meals — LeetCode 1711 Python Solution
- Problem
- #1711
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- deliciousness = [1,3,5,7,9]
- Output
- 4
- Explanation
- The good meals are (1,3), (1,7), (3,5) and, (7,9).
Python solution
class Solution:
def countPairs(self, deliciousness: List[int]) -> int:
mod = 10**9 + 7
mx = max(deliciousness) << 1
cnt = Counter()
ans = 0
for d in deliciousness:
s = 1
while s <= mx:
ans = (ans + cnt[s - d]) % mod
s <<= 1
cnt[d] += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log M), where n is the length of the array `deliciousness`, and M is the upper limit of the elements |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1711. Count Good Meals is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1711. Count Good Meals?
- LeetCode 1711. Count Good Meals is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1711. Count Good Meals?
- The Python solution on this page runs in O(n \times \log M), where n is the length of the array `deliciousness`, and M is the upper limit of the elements.
- What is the space complexity of LeetCode 1711. Count Good Meals?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1711. Count Good Meals cover?
- LeetCode 1711. Count Good Meals is tagged Array and Hash Table on LeetCode.