Minimize operations to empty Array by deleting two unequal elements or one element
Last Updated :
02 Jan, 2023
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 <bits/stdc++.h>
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<pair<int, int> > 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<pair> {
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<Integer, Integer> freq = new HashMap<>();
List<pair> arrPos = new ArrayList<>();
List<pair> 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<Integer, Integer> 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;
// Function call
System.out.print(minOperationToEmpty(A, N));
}
}
// This code is contributed by lokeshmvs21.
Python3
# Function to find minimum number of
# operations to empty the array
def minOperationToEmpty(A, N):
OpCnt = 0
freq = {}
for z in range(0,10):
freq[z] = 0
arrPos = []
optimalPairs = []
# Loop to find the frequency
for i in range(0,N):
freq[A[i]] = freq[A[i]]+1
for i in range(0,10):
if(freq[i]>0):
arrPos.append([ freq[i], i ])
# Sort based on frequency
arrPos.sort()
# Find the unequal elements pairs
for i in range(len(arrPos)-1,0,-1):
j = i - 1
while (arrPos[i][0] != 0 and j >= 0):
temp = min(arrPos[i][0], arrPos[j][0])
loop = temp
while (loop>0):
optimalPairs.append([ arrPos[i][1], arrPos[j][1] ])
loop-=1
OpCnt += temp
arrPos[i][0] -= temp
arrPos[j][0] -= temp
j-=1
# Loop to find equal valued pairs
for i in range(0,len(arrPos)):
if (arrPos[i][0]>0):
OpCnt += arrPos[i][0]
break
# Loop to assign equal elements with unequal pairs
for j in range(0,len(optimalPairs)):
if(arrPos[i][0] >= -1):
break
if (optimalPairs[j][0] != arrPos[i][1] and optimalPairs[j][1] != arrPos[i][1]):
OpCnt -= 1
arrPos[i][0] -= 2
return OpCnt
# Driver code
A = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
N = len(A)
# Function Call
print(minOperationToEmpty(A, N))
# This code is contributed by akashish__
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<KeyValuePair<int, int> >();
var optimalPairs
= new List<KeyValuePair<int, int> >();
// 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.
JavaScript
// JS code to implement the approach
// Function to find minimum number of
// operations to empty the array
function minOperationToEmpty(A, N) {
let j, i, OpCnt = 0;
let freq = new Map();
let arrPos = [];
let optimalPairs = [];
// Loop to find the frequency
for (i = 0; i < N; i++)
freq.set(A[i], 1);
for (let [key, value] of freq) {
arrPos.push({
"first": value,
"second": key
});
}
// Sort based on frequency
arrPos.sort();
// Find the unequal elements pairs
for (i = arrPos.length - 1; i >= 1; i--) {
j = i - 1;
while (arrPos[i].first != 0 && j >= 0) {
let temp
= Math.min(arrPos[i].first, arrPos[j].first);
let loop = temp;
while (loop--)
optimalPairs.push(
{
"first": arrPos[i].second,
"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.length; i++) {
if (arrPos[i].first) {
OpCnt += arrPos[i].first;
break;
}
}
i = i - 1;
// Loop to assign equal elements with unequal pairs
for (j = 0; j < optimalPairs.length
&& 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
let A = [1, 2, 3, 4, 5, 6, 7, 8];
let N = A.length;
// Function Call
console.log(minOperationToEmpty(A, N));
// This code is contributed by akashish__
Time Complexity: O(N * log N)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read