Minimum number of elements that should be removed to make the array good

Given an array arr[], the task is to find the minimum number of elements that must be removed to make the array good. A sequence a1, a2 … an is called good if for each element ai, there exists an element aj (i not equals to j) such that ai + aj is a power of two i.e. 2d for some non-negative integer d.

Examples:

Input: arr[] = {4, 7, 1, 5, 4, 9}
Output: 1
Remove 5 from the array to make the array good.

Input: arr[] = {1, 3, 1, 1}
Output: 0

Approach: We should delete only such ai for which there is no aj (i not equals to j) such that ai + aj is a power of 2.
For each value let’s find the number of its occurrences in the array. We can use the map data-structure.

Now we can easily check that ai doesn’t have a pair aj. Let’s iterate over all possible sums, S = 20, 21, …, 230 and for each S calculate S – a[i] whether it exists in the map.

Below is the implementation of the above approach :

filter_none

edit
close

play_arrow

link
brightness_4
code

chevron_right


Output:

1


My Personal Notes arrow_drop_up