Skip to content

1830. Count Good Meals

Difficulty: Medium

LeetCode Problem View on GitHub


1830. Count Good Meals

Medium


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.

Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i​​​​​​th​​​​​​​​ item of food, return the number of different good meals you can make from this list modulo 109 + 7.

Note that items with different indices are considered different even if they have the same deliciousness value.

 

Example 1:

Input: deliciousness = [1,3,5,7,9]
Output: 4
Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9).
Their respective sums are 4, 8, 8, and 16, all of which are powers of 2.

Example 2:

Input: deliciousness = [1,1,1,3,3,3,7]
Output: 15
Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.

 

Constraints:

  • 1 <= deliciousness.length <= 105
  • 0 <= deliciousness[i] <= 220

Solution

import java.util.Arrays;
import java.util.HashMap;

class Solution {
    private int mod = 1000000007;
    public int countPairs(int[] arr) {
        int n = arr.length;
        Arrays.sort(arr);
        HashMap<Integer, Integer> map = new HashMap<>();
        int count = 0, pow2Count = 0;
        for (int i = 0; i < n; i++) {
            int current = arr[i];
            if (arr[i] == 0) {
                count = (count + pow2Count) % mod;
                map.put(0, map.getOrDefault(0, 0) + 1);
                continue;
            }
            if (current > 0 && (current & (current - 1)) == 0) {
                pow2Count++;
                count = (count + map.getOrDefault(current, 0)) % mod;
                count = (count + map.getOrDefault(0, 0)) % mod;
            } else {
                /* Find the first number which is power of 2 and is greater than current */
                int mask = 1;
                while (mask < current)
                    mask = mask << 1;
                int req = mask - current;
                count = (count + map.getOrDefault(req, 0)) % mod;
            }
            map.put(current, map.getOrDefault(current, 0) + 1);
        }
        return count;
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Approach

Detailed explanation of the approach will be added here