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

Last Updated : 31 Oct, 2023

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:
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 :

## C++

 `// C++ implementation of the approach` `#include ` `using` `namespace` `std;`   `// Function to return the minimum number` `// of elements that must be removed` `// to make the given array good` `int` `minimumRemoval(``int` `n, ``int` `a[])` `{`   `    ``map<``int``, ``int``> c;`   `    ``// Count frequency of each element` `    ``for` `(``int` `i = 0; i < n; i++)` `        ``c[a[i]]++;`   `    ``int` `ans = 0;`   `    ``// For each element check if there` `    ``// exists another element that makes` `    ``// a valid pair` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``bool` `ok = ``false``;` `        ``for` `(``int` `j = 0; j < 31; j++) {` `            ``int` `x = (1 << j) - a[i];` `            ``if` `(c.count(x) && (c[x] > 1` `                       ``|| (c[x] == 1 && x != a[i]))) {` `                ``ok = ``true``;` `                ``break``;` `            ``}` `        ``}`   `        ``// If does not exist then` `        ``// increment answer` `        ``if` `(!ok)` `            ``ans++;` `    ``}`   `    ``return` `ans;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `a[] = { 4, 7, 1, 5, 4, 9 };` `    ``int` `n = ``sizeof``(a) / ``sizeof``(a[0]);` `    ``cout << minimumRemoval(n, a);`   `    ``return` `0;` `}`

## Java

 `// Java implementation of the approach` `import` `java.util.*;`   `class` `GFG ` `{`   `// Function to return the minimum number` `// of elements that must be removed` `// to make the given array good` `static` `int` `minimumRemoval(``int` `n, ``int` `a[])` `{`   `    ``Map c = ``new` `HashMap<>();`   `    ``// Count frequency of each element` `    ``for` `(``int` `i = ``0``; i < n; i++)` `        ``if``(c.containsKey(a[i]))` `        ``{` `            ``c.put(a[i], c.get(a[i])+``1``);` `        ``}` `        ``else` `        ``{` `            ``c.put(a[i], ``1``);` `        ``}`   `    ``int` `ans = ``0``;`   `    ``// For each element check if there` `    ``// exists another element that makes` `    ``// a valid pair` `    ``for` `(``int` `i = ``0``; i < n; i++) ` `    ``{` `        ``boolean` `ok = ``false``;` `        ``for` `(``int` `j = ``0``; j < ``31``; j++)` `        ``{` `            ``int` `x = (``1` `<< j) - a[i];` `            ``if` `((c.get(x) != ``null` `&& (c.get(x) > ``1``)) ||` `                ``c.get(x) != ``null` `&& (c.get(x) == ``1` `&& x != a[i])) ` `            ``{` `                ``ok = ``true``;` `                ``break``;` `            ``}` `        ``}`   `        ``// If does not exist then` `        ``// increment answer` `        ``if` `(!ok)` `            ``ans++;` `    ``}`   `    ``return` `ans;` `}`   `// Driver code` `public` `static` `void` `main(String[] args)` `{` `    ``int` `a[] = { ``4``, ``7``, ``1``, ``5``, ``4``, ``9` `};` `    ``int` `n = a.length;` `    ``System.out.println(minimumRemoval(n, a));` `}` `}`   `/* This code contributed by PrinciRaj1992 */`

## Python3

 `# Python3 implementation of the approach `   `# Function to return the minimum number ` `# of elements that must be removed ` `# to make the given array good ` `def` `minimumRemoval(n, a) :`   `    ``c ``=` `dict``.fromkeys(a, ``0``);`   `    ``# Count frequency of each element ` `    ``for` `i ``in` `range``(n) :` `        ``c[a[i]] ``+``=` `1``; `   `    ``ans ``=` `0``; `   `    ``# For each element check if there ` `    ``# exists another element that makes ` `    ``# a valid pair ` `    ``for` `i ``in` `range``(n) :` `        ``ok ``=` `False``; ` `        ``for` `j ``in` `range``(``31``) :` `            `  `            ``x ``=` `(``1` `<< j) ``-` `a[i]; ` `            ``if` `(x ``in` `c ``and` `(c[x] > ``1` `or` `               ``(c[x] ``=``=` `1` `and` `x !``=` `a[i]))) :` `                `  `                ``ok ``=` `True``; ` `                ``break``;`   `        ``# If does not exist then ` `        ``# increment answer ` `        ``if` `(``not` `ok) :` `            ``ans ``+``=` `1``; ` `            `  `    ``return` `ans; `   `# Driver Code` `if` `__name__ ``=``=` `"__main__"` `:` `    `  `    ``a ``=` `[ ``4``, ``7``, ``1``, ``5``, ``4``, ``9` `]; ` `    ``n ``=` `len``(a) ; ` `    `  `    ``print``(minimumRemoval(n, a));` `    `  `# This code is contributed by Ryuga`

## C#

 `// C# implementation of the approach` `using` `System.Linq;` `using` `System;`   `class` `GFG` `{` `// Function to return the minimum number` `// of elements that must be removed` `// to make the given array good` `static` `int` `minimumRemoval(``int` `n, ``int` `[]a)` `{`   `    ``int``[] c = ``new` `int``[1000];`   `    ``// Count frequency of each element` `    ``for` `(``int` `i = 0; i < n; i++)` `        ``c[a[i]]++;`   `    ``int` `ans = 0;`   `    ``// For each element check if there` `    ``// exists another element that makes` `    ``// a valid pair` `    ``for` `(``int` `i = 0; i < n; i++) ` `    ``{` `        ``bool` `ok = ``true``;` `        ``for` `(``int` `j = 0; j < 31; j++) ` `        ``{` `            ``int` `x = (1 << j) - a[i];` `            ``if` `(c.Contains(x) && (c[x] > 1 ||` `                    ``(c[x] == 1 && x != a[i]))) ` `            ``{` `                ``ok = ``false``;` `                ``break``;` `            ``}` `        ``}`   `        ``// If does not exist then` `        ``// increment answer` `        ``if` `(!ok)` `            ``ans++;` `    ``}`   `    ``return` `ans;` `}`   `// Driver code` `static` `void` `Main()` `{` `    ``int` `[]a = { 4, 7, 1, 5, 4, 9 };` `    ``int` `n = a.Length;` `    ``Console.WriteLine(minimumRemoval(n, a));` `}` `}`   `// This code is contributed by mits`

## Javascript

 ``

Output

```1

```

Time Complexity: O(nlogn)
Auxiliary Space: O(n)

Another Approach:

1. Create a function “isPowerOfTwo” to check if a number is a power of two.
2. Create a function “countRemovedElements” that takes an array as input and returns the minimum number of elements that must be removed to make the array good.
3. Initialize a count variable to keep track of the number of removed elements.
4. Loop through the array and for each element, check if there exists another element in the array that can form a power of two with it.
5. If such an element is found, continue to the next element in the array.
6. If no such element is found, increment the count variable.
7. Return the count of removed elements.
8. In the “main” function, create an example array and call the “countRemovedElements” function to get the minimum number of elements that must be removed to make the array good.
9. Print the output.

Below is the implementation of the above approach:

## C++

 `#include ` `#include ` `#include `   `using` `namespace` `std;`   `// function to check if a number is a power of two` `bool` `isPowerOfTwo(``int` `x) {` `    ``return` `(x && !(x & (x - 1)));` `}`   `// function to count the minimum number of elements that must be removed to make the array good` `int` `countRemovedElements(vector<``int``>& arr) {` `    ``int` `n = arr.size();` `    ``int` `count = 0;` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``bool` `found = ``false``;` `        ``// loop through the array to find another element that ` `       ``// can form a power of two with the current element` `        ``for` `(``int` `j = 0; j < n; j++) {` `            ``// check if the current element is not the same as the other element, ` `           ``// and their sum is a power of two` `            ``if` `(i != j && isPowerOfTwo(arr[i] + arr[j])) {` `                ``found = ``true``;` `                ``break``;` `            ``}` `        ``}` `        ``// if no other element is found to form a power of two with ` `       ``// the current element, increment the count of removed elements` `        ``if` `(!found) {` `            ``count++;` `        ``}` `    ``}` `    ``// return the count of removed elements` `    ``return` `count;` `}`   `int` `main() {` `    ``// example array` `    ``vector<``int``> arr = {4, 7, 1, 5, 4, 9};` `    ``// call the function to count the minimum number of elements ` `   ``// that must be removed to make the array good` `    ``cout << countRemovedElements(arr) << endl; ``// Output: 1` `    `  `    ``return` `0;` `}` `//This code is contributed by rudra1807raj`

## Java

 `import` `java.util.*;`   `public` `class` `Main {` `    ``// function to check if a number is a power of two` `    ``public` `static` `boolean` `isPowerOfTwo(``int` `x)` `    ``{` `        ``return` `(x & (x - ``1``)) == ``0``;` `    ``}`   `    ``// function to count the minimum number of elements that` `    ``// must be removed to make the array good` `    ``public` `static` `int` `    ``countRemovedElements(ArrayList arr)` `    ``{` `        ``int` `n = arr.size();` `        ``int` `count = ``0``;` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``boolean` `found = ``false``;` `            ``// loop through the array to find another` `            ``// element that can form a power of two with the` `            ``// current element` `            ``for` `(``int` `j = ``0``; j < n; j++) {` `                ``// check if the current element is not the` `                ``// same as the other element, and their sum` `                ``// is a power of two` `                ``if` `(i != j` `                    ``&& isPowerOfTwo(arr.get(i)` `                                    ``+ arr.get(j))) {` `                    ``found = ``true``;` `                    ``break``;` `                ``}` `            ``}` `            ``// if no other element is found to form a power` `            ``// of two with the current element, increment` `            ``// the count of removed elements` `            ``if` `(!found) {` `                ``count++;` `            ``}` `        ``}` `        ``// return the count of removed elements` `        ``return` `count;` `    ``}`   `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``// example array` `        ``ArrayList arr = ``new` `ArrayList<>(` `            ``Arrays.asList(``4``, ``7``, ``1``, ``5``, ``4``, ``9``));` `        ``// call the function to count the minimum number of` `        ``// elements that must be removed to make the array` `        ``// good` `        ``System.out.println(` `            ``countRemovedElements(arr)); ``// Output: 1` `    ``}` `}`

## Python3

 `import` `math`   `# function to check if a number is a power of two` `def` `isPowerOfTwo(x):` `    ``return` `(x ``and` `not` `(x & (x ``-` `1``)))`   `# function to count the minimum number of elements ` `# that must be removed to make the array good` `def` `countRemovedElements(arr):` `    ``n ``=` `len``(arr)` `    ``count ``=` `0` `    ``for` `i ``in` `range``(n):` `        ``found ``=` `False` `        ``# loop through the array to find another element ` `        ``# that can form a power of two with the current element` `        ``for` `j ``in` `range``(n):` `            ``# check if the current element is not ` `            ``# the same as the other element, and ` `            ``# their sum is a power of two` `            ``if` `i !``=` `j ``and` `isPowerOfTwo(arr[i] ``+` `arr[j]):` `                ``found ``=` `True` `                ``break` `        ``# if no other element is found to form ` `        ``# a power of two with the current element, ` `        ``# increment the count of removed elements` `        ``if` `not` `found:` `            ``count ``+``=` `1` `    ``# return the count of removed elements` `    ``return` `count`     `# example array` `arr ``=` `[``4``, ``7``, ``1``, ``5``, ``4``, ``9``]`   `# call the function to count the minimum number of elements ` `# that must be removed to make the array good` `print``(countRemovedElements(arr))  ``# Output: 1`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `class` `Program` `{` `    ``// Function to check if a number is a power of two` `    ``static` `bool` `IsPowerOfTwo(``int` `x)` `    ``{` `        ``return` `(x != 0) && ((x & (x - 1)) == 0);` `    ``}`   `    ``// Function to count the minimum number of elements that must be removed to make the array good` `    ``static` `int` `CountRemovedElements(List<``int``> arr)` `    ``{` `        ``int` `n = arr.Count;` `        ``int` `count = 0;`   `        ``for` `(``int` `i = 0; i < n; i++)` `        ``{` `            ``bool` `found = ``false``;`   `            ``// Loop through the array to find another element that can form a power of two with the current element` `            ``for` `(``int` `j = 0; j < n; j++)` `            ``{` `                ``// Check if the current element is not the same as the other element,` `                ``// and their sum is a power of two` `                ``if` `(i != j && IsPowerOfTwo(arr[i] + arr[j]))` `                ``{` `                    ``found = ``true``;` `                    ``break``;` `                ``}` `            ``}`   `            ``// If no other element is found to form a power of two with the current element, increment the count of removed elements` `            ``if` `(!found)` `            ``{` `                ``count++;` `            ``}` `        ``}`   `        ``// Return the count of removed elements` `        ``return` `count;` `    ``}`   `    ``static` `void` `Main()` `    ``{` `        ``// Example list` `        ``List<``int``> arr = ``new` `List<``int``> { 4, 7, 1, 5, 4, 9 };`   `        ``// Call the function to count the minimum number of elements that must be removed to make the list good` `        ``Console.WriteLine(CountRemovedElements(arr)); ``// Output: 1` `    ``}` `}`

## Javascript

 `// Function to check if a number is a power of two` `function` `isPowerOfTwo(x) {` `    ``return` `(x && !(x & (x - 1)));` `}`   `// Function to count the minimum number of elements that must be removed to make the array good` `function` `countRemovedElements(arr) {` `    ``const n = arr.length;` `    ``let count = 0;` `    `  `    ``for` `(let i = 0; i < n; i++) {` `        ``let found = ``false``;` `        `  `        ``// Loop through the array to find another element that can form a power of two with the current element` `        ``for` `(let j = 0; j < n; j++) {` `            ``// Check if the current element is not the same as the other element, and their sum is a power of two` `            ``if` `(i !== j && isPowerOfTwo(arr[i] + arr[j])) {` `                ``found = ``true``;` `                ``break``;` `            ``}` `        ``}` `        `  `        ``// If no other element is found to form a power of two with the current element, increment the count of removed elements` `        ``if` `(!found) {` `            ``count++;` `        ``}` `    ``}` `    `  `    ``// Return the count of removed elements` `    ``return` `count;` `}`   `// Example array` `const arr = [4, 7, 1, 5, 4, 9];`   `// Call the function to count the minimum number of elements that must be removed to make the array good` `console.log(countRemovedElements(arr)); ``// Output: 1`   `// This code is contributed by shivamgupta0987654321`

Output

```1

```

Time Complexity: The time complexity of the given code is O(n^2), where n is the size of the input array. This is because the code contains a nested loop, where for each element in the array, it loops through the entire array to find another element that can form a power of two with it. Therefore, the time complexity is proportional to the square of the input size.

Auxiliary Space: The space complexity of the code is O(1) because the code uses only a constant amount of additional memory to perform its operations, regardless of the size of the input array. The code does not create any additional data structures or use any recursive calls, and therefore the amount of memory used is constant.

Previous
Next