The Count Good Meals interview question defines a "good meal" as a pair of items from a list whose prices sum up to a power of 2 (e.g., 1, 2, 4, 8, ...). Given an array of prices, you need to count how many pairs (i, j) form a good meal. You need to return the result modulo 10^9 + 7.
Swiggy and Robinhood use the Hash Table interview pattern for this problem to test your ability to optimize a "Two Sum" variation. Instead of a single target, you have multiple targets (all powers of 2 up to 2^21). It evaluates if you can efficiently check all potential targets for each element in the array.
This is a Two Sum variation using a Hash Map.
p, iterate through all possible powers of 2 (from 1 to 2^21).complement = power_of_2 - p.complement in your Hash Map and add it to the total.p in the map.prices = [1, 3, 5]
p = 1: No complements in map. Add {1: 1}.p = 3: Target 4. 4 - 3 = 1. 1 is in map! Count += 1. Add {3: 1}.p = 5: Target 8. 8 - 5 = 3. 3 is in map! Count += 1. Add {5: 1}.
Total = 2.Always use a single-pass Hash Map approach for "Pair Sum" problems. By checking the complement against what's already in the map and then adding the current element, you automatically avoid counting a pair twice or counting an element with itself.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| 4Sum II | Medium | Solve | |
| Assign Elements to Groups with Constraints | Medium | Solve | |
| Brick Wall | Medium | Solve | |
| Card Flipping Game | Medium | Solve | |
| Convert an Array Into a 2D Array With Conditions | Medium | Solve |