# Minimize operations to empty Array by deleting two unequal elements or one element

• Difficulty Level : Expert
• Last Updated : 01 Dec, 2022

Given an array A of size N, the task is to find the minimum number of operations required to make array A empty. The following operations can be performed:

• Choose any two elements, say X and Y, from A such that X != Y and remove them.
• Otherwise, choose any one element, say X, from A and remove it.

Examples:

Input: N = 2, A = {2, 2}
Output: 2
Explanation: Remove both values separately and
it will cost a total of 2 operations.

Input: N = 2, A = {1, 2}
Output: 1
Explanation: Remove both values together in one operation
and it will cost a total of 1 operation.

Input: N = 6, A = {2, 2, 2, 2, 3, 3}
Output: 4
Explanation: Remove A[0] and A[5] to get A = {2, 2, 2, 3}.
Remove A[0] and A[3] to get A = {2, 2}.
Remove A[0] to get A = {2}.
Remove A[0] to get A = {}.

Approach: The problem can be solved based on the below observation:

It can be observed that if any two elements can be removed simultaneously then it’s best to choose a pair with {Element with maximum frequency, Element with second maximum frequency} at each operation. The last remaining element has to be checked if it can be matched with any non-equal element pairs that are already formed. \

Eventually, If the pairs come to be equal then we have exhausted all pairs with different elements and only equal elements are remaining which can only be removed using separate operations.

Follow the given steps to solve the problem:

• Traverse array A[] and store all frequencies in a map freq.
• Push all {frequency, element} pairs into an array of pairs (say arrPos[]).
• Sort arrPos based on frequencies.
• Traverse arrPos in reverse order (say i) with j = i – 1.
• Traverse in a nested order until frequency at arrPos[i] is not 0 and j â‰¥ 0.
• Store all formed pairs in an array pair (say optimalPairs[]).
• Add minimum of frequency at arrPos[i] and arrPos[j] to OpCnt.
• Subtract minimum of frequency at arrPos[i] and arrPos[j] from frequency of arrPos[i] and arrPos[j] and decrement j.
• Traverse arrPos[] again to find the non-zero frequency and break after adding that frequency at arrPos[i] to OpCnt.
• Traverse pair optimalPairs and decrement OpCnt by 1 and frequency at arrPos[i] by 2 if the remaining element at arrPos[i] is not equal to the pair in optimalPairs.
• Return OpCnt as the final answer.

Below is the Implementation of this approach:

## C++14

 `// C++ code to implement the approach`   `#include ` `using` `namespace` `std;`   `// Function to find minimum number of` `// operations to empty the array` `int` `minOperationToEmpty(``int``* A, ``int``& N)` `{` `    ``int` `j, i, OpCnt = 0;` `    ``unordered_map<``int``, ``int``> freq;` `    ``vector > arrPos, optimalPairs;`   `    ``// Loop to find the frequency` `    ``for` `(i = 0; i < N; i++)` `        ``freq[A[i]]++;`   `    ``for` `(``auto``& x : freq)` `        ``arrPos.push_back({ x.second, x.first });`   `    ``// Sort based on frequency` `    ``sort(arrPos.begin(), arrPos.end());`   `    ``// Find the unequal elements pairs` `    ``for` `(i = arrPos.size() - 1; i >= 1; i--) {` `        ``j = i - 1;` `        ``while` `(arrPos[i].first != 0 && j >= 0) {` `            ``int` `temp` `                ``= min(arrPos[i].first, arrPos[j].first);` `            ``int` `loop = temp;` `            ``while` `(loop--)` `                ``optimalPairs.push_back(` `                    ``{ arrPos[i].second, arrPos[j].second });`   `            ``OpCnt += temp;` `            ``arrPos[i].first -= temp;` `            ``arrPos[j--].first -= temp;` `        ``}` `    ``}`   `    ``// Loop to find equal valued pairs` `    ``for` `(i = 0; i < arrPos.size(); i++) {` `        ``if` `(arrPos[i].first) {` `            ``OpCnt += arrPos[i].first;` `            ``break``;` `        ``}` `    ``}` `    ``// Loop to assign equal elements with unequal pairs` `    ``for` `(j = 0; j < optimalPairs.size()` `                ``&& arrPos[i].first >= 2;` `         ``j++) {` `        ``if` `(optimalPairs[j].first != arrPos[i].second` `            ``&& optimalPairs[j].second != arrPos[i].second) {` `            ``OpCnt--;` `            ``arrPos[i].first -= 2;` `        ``}` `    ``}` `    ``return` `OpCnt;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `A[] = { 1, 2, 3, 4, 5, 6, 7, 8 };` `    ``int` `N = ``sizeof``(A) / ``sizeof``(A[0]);`   `    ``// Function Call` `    ``cout << minOperationToEmpty(A, N);` `    ``return` `0;` `}`

## Java

 `// Java code to implement the approach`   `import` `java.io.*;` `import` `java.util.*;`   `class` `pair {` `    ``int` `first, second;` `    ``pair(``int` `first, ``int` `second)` `    ``{` `        ``this``.first = first;` `        ``this``.second = second;` `    ``}` `}`   `class` `GFG {`   `    ``static` `class` `Sorting ``implements` `Comparator {` `        ``public` `int` `compare(pair p1, pair p2)` `        ``{` `            ``if` `(p2.second == p1.second) {` `                ``return` `p2.first - p1.first;` `            ``}` `            ``return` `p2.second - p1.second;` `        ``}` `    ``}`   `    ``// Function to find minimum number of` `    ``// operations to empty the array` `    ``static` `int` `minOperationToEmpty(``int``[] A, ``int` `N)` `    ``{` `        ``int` `j, i, OpCnt = ``0``;` `        ``HashMap freq = ``new` `HashMap<>();` `        ``List arrPos = ``new` `ArrayList<>();` `        ``List optimalPairs = ``new` `ArrayList<>();`   `        ``// Loop to find the frequency` `        ``for` `(i = ``0``; i < N; i++) {` `            ``freq.put(A[i], freq.getOrDefault(A[i], ``0``) + ``1``);` `        ``}`   `        ``for` `(Map.Entry x :` `             ``freq.entrySet()) {` `            ``arrPos.add(``new` `pair(x.getValue(), x.getKey()));` `        ``}`   `        ``// Sort based on frequency` `        ``Collections.sort(arrPos, ``new` `Sorting());`   `        ``// Find the unequal elements pairs` `        ``for` `(i = arrPos.size() - ``1``; i >= ``1``; i--) {` `            ``j = i - ``1``;` `            ``while` `(arrPos.get(i).first != ``0` `&& j >= ``0``) {` `                ``int` `temp = Math.min(arrPos.get(i).first,` `                                    ``arrPos.get(j).first);` `                ``int` `loop = temp;` `                ``while` `(loop-- > ``0``) {` `                    ``optimalPairs.add(` `                        ``new` `pair(arrPos.get(i).second,` `                                 ``arrPos.get(j).second));` `                ``}` `                ``OpCnt += temp;` `                ``arrPos.get(i).first -= temp;` `                ``arrPos.get(j).first -= temp;` `                ``j--;` `            ``}` `        ``}`   `        ``// Loop to find equal valued pairs` `        ``for` `(i = ``0``; i < arrPos.size(); i++) {` `            ``if` `(arrPos.get(i).first > ``0``) {` `                ``OpCnt += arrPos.get(i).first;` `                ``break``;` `            ``}` `        ``}`   `        ``return` `OpCnt;` `    ``}`   `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int``[] A = { ``1``, ``2``, ``3``, ``4``, ``5``, ``6``, ``7``, ``8` `};` `        ``int` `N = A.length;`   `        ``// Fucntion call` `        ``System.out.print(minOperationToEmpty(A, N));` `    ``}` `}`   `// This code is contributed by lokeshmvs21.`

## C#

 `// C# code to implement the approach` `using` `System;` `using` `System.Collections.Generic;` `class` `GFG {` `    ``static` `int` `Compare(KeyValuePair<``int``, ``int``> a,` `                       ``KeyValuePair<``int``, ``int``> b)` `    ``{` `        ``return` `a.Key.CompareTo(b.Key);` `    ``}` `  `  `    ``// Function to find minimum number of` `    ``// operations to empty the array` `    ``static` `int` `minOperationToEmpty(``int``[] A, ``int` `N)` `    ``{` `        ``int` `j, i, OpCnt = 0;` `        ``Dictionary<``int``, ``int``> freq` `            ``= ``new` `Dictionary<``int``, ``int``>();` `        ``var` `arrPos = ``new` `List >();` `        ``var` `optimalPairs` `            ``= ``new` `List >();`   `        ``// Loop to find the frequency` `        ``for` `(i = 0; i < N; i++) {` `            ``if` `(freq.ContainsKey(A[i])) {` `                ``var` `val = freq[A[i]];` `                ``freq.Remove(A[i]);` `                ``freq.Add(A[i], val + 1);` `            ``}` `            ``else` `                ``freq.Add(A[i], 1);` `        ``}` `        ``foreach``(``var` `e ``in` `freq) arrPos.Add(` `            ``new` `KeyValuePair<``int``, ``int``>(e.Value, e.Key));`   `        ``// Sort based on frequency` `        ``arrPos.Sort(Compare);`   `        ``// Find the unequal elements pairs` `        ``for` `(i = arrPos.Count - 1; i >= 1; i--) {` `            ``j = i - 1;` `            ``while` `(arrPos[i].Key != 0 && j >= 0) {` `                ``int` `temp = Math.Min(arrPos[i].Key,` `                                    ``arrPos[j].Key);` `                ``int` `loop = temp;` `                ``while` `(loop-- != 0)` `                    ``optimalPairs.Add(` `                        ``new` `KeyValuePair<``int``, ``int``>(` `                            ``arrPos[i].Value,` `                            ``arrPos[j].Value));`   `                ``OpCnt += temp;` `                ``var` `p = ``new` `KeyValuePair<``int``, ``int``>(` `                    ``arrPos[i].Key - temp, arrPos[i].Value);` `                ``arrPos[i] = p;` `                ``p = ``new` `KeyValuePair<``int``, ``int``>(` `                    ``arrPos[j].Key - temp, arrPos[j].Value);` `                ``arrPos[j] = p;` `                ``j--;` `            ``}` `        ``}`   `        ``// Loop to find equal valued pairs` `        ``for` `(i = 0; i < arrPos.Count; i++) {` `            ``if` `(arrPos[i].Key != 0) {` `                ``OpCnt += arrPos[i].Key;` `                ``break``;` `            ``}` `        ``}`   `        ``// Loop to assign equal elements with unequal pairs` `        ``for` `(j = 0;` `             ``j < optimalPairs.Count && i < arrPos.Count` `             ``&& arrPos[i].Key >= 2;` `             ``j++) {` `            ``if` `(optimalPairs[j].Key != arrPos[i].Value` `                ``&& optimalPairs[j].Value` `                       ``!= arrPos[i].Value) {` `                ``OpCnt--;` `                ``Console.WriteLine(i);` `                ``var` `p = ``new` `KeyValuePair<``int``, ``int``>(` `                    ``arrPos[i].Key - 2, arrPos[i].Value);` `                ``arrPos[i] = p;` `            ``}` `        ``}` `        ``return` `OpCnt;` `    ``}` `    ``static` `void` `Main()` `    ``{`   `        ``int``[] A = { 1, 2, 3, 4, 5, 6, 7, 8 };` `        ``int` `N = A.Length;`   `        ``// Function Call` `        ``Console.Write(minOperationToEmpty(A, N));` `    ``}` `}`   `// This code is contributed by garg28harsh.`

Output

`4`

Time Complexity: O(N * log N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Related Articles