Minimize deletion or append to make consecutive occurrence of all elements equal
Given an array arr[] of size N having positive elements, the task is to find the minimum number of deletion or append operations to make consecutive occurrences of all elements equal.
Examples:
Input: N = 4, arr[] = {1, 1, 2, 2}
Output: 0
Explanation: All the consecutive elements have the same value and same frequency already. Therefore, no operation is required.
Input: N = 8, arr[] = {5, 5, 5, 6, 2, 2, 5, 5},
Output: 2
Explanation:
First Operation: Choose i = 3 and put 6 at right side of i. Then updated arr[] is: {5, 5, 5, 6, 6, 2, 2, 5, 5}.
Second Operation: Choose i = 2 and remove it from arr[]. Then updated arr[] is: {5, 5, 6, 6, 2, 2, 5, 5}.
Approach: Implement the idea below to solve the problem
The problem can be solved is based on the mathematical concept of the median value.
In N numbers, the median is the number that has the least sum difference from all of the numbers present. Same in the problem we have to find the minimum number of operations such that all the elements have the same frequency. Therefore, we need to find a frequency of an element which has the least sum difference from all of the present frequencies. So, we can use the concept of the median here.
Follow the below illustration for a better understanding.
Illustration:
Consider N = 8, arr[] = {5, 5, 5, 6, 2, 2, 5, 5}
Frequencies of same consecutive elements: {5: 3, 6: 1, 2: 2, 5: 2}, get all the frequencies in Frequency array.
Frequency[] = {3, 1, 2, 2}
Sorted frequency[] = {1, 2, 2, 3}
median = Frequency[frequency.Length/2] = frequency[4/2] = frequency[2] = 2
Absolute difference of all numbers with median:
|1 – 2|=1
|2 – 2|=0
|2 – 2|=0
|3 – 2|=1
Sum of absolute differences = Minimum number of operations required = 1+0+0+1 = 2
Total operations = 2
Follow the below steps to implement the idea:
- Create an ArrayList to hold frequencies, let us say frequency[].
- Traverse on input arr[], get frequencies of consecutive elements having the same value and store them in frequency.
- If frequency.size() = 1, Return minimum cost as 0.
- Else calculate the sum of differences from the median and return the sum of differences.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int MinCost( int arr[], int n)
{
vector< int > frequencies;
int leftEnd = 1;
int count = 1;
int prev = arr[0];
while (leftEnd < n) {
if (prev == arr[leftEnd]) {
count++;
}
else {
frequencies.push_back(count);
count = 1;
prev = arr[leftEnd];
}
leftEnd++;
}
frequencies.push_back(count);
sort(frequencies.begin(), frequencies.end());
if (frequencies.size() == 1) {
return 0;
}
else {
int median = frequencies[frequencies.size() / 2];
int operations = 0;
for ( int i = 0; i < frequencies.size(); i++) {
operations += abs (frequencies[i] - median);
}
return operations;
}
}
int main()
{
int N = 8;
int arr[] = { 5, 5, 5, 6, 2, 2, 5, 5 };
cout << (MinCost(arr, N));
}
|
Java
import java.lang.*;
import java.util.ArrayList;
class GFG {
public static void main(String[] args)
{
int N = 8 ;
int [] arr = { 5 , 5 , 5 , 6 , 2 , 2 , 5 , 5 };
System.out.println(MinCost(arr, N));
}
static int MinCost( int [] arr, int n)
{
ArrayList<Integer> frequencies = new ArrayList<>();
int leftEnd = 1 ;
int count = 1 ;
int prev = arr[ 0 ];
while (leftEnd < n) {
if (prev == arr[leftEnd]) {
count++;
}
else {
frequencies.add(count);
count = 1 ;
prev = arr[leftEnd];
}
leftEnd++;
}
frequencies.add(count);
frequencies.sort( null );
if (frequencies.size() == 1 ) {
return 0 ;
}
else {
int median
= frequencies.get(frequencies.size() / 2 );
int operations = 0 ;
for ( int i = 0 ; i < frequencies.size(); i++) {
operations += Math.abs(frequencies.get(i)
- median);
}
return operations;
}
}
}
|
Python3
def MinCost(arr, n):
frequencies = []
leftEnd = 1
count = 1
prev = arr[ 0 ]
while leftEnd < n:
if prev = = arr[leftEnd]:
count + = 1
else :
frequencies.append(count)
count = 1
prev = arr[leftEnd]
leftEnd + = 1
frequencies.append(count)
frequencies.sort()
if len (frequencies) = = 1 :
return 0
else :
median = frequencies[ len (frequencies) / / 2 ]
operations = 0
for i in range ( len (frequencies)):
operations + = abs (frequencies[i] - median)
return operations
N = 8
arr = [ 5 , 5 , 5 , 6 , 2 , 2 , 5 , 5 ]
print (MinCost(arr, N))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static public void Main()
{
int N = 8;
int [] arr = { 5, 5, 5, 6, 2, 2, 5, 5 };
Console.WriteLine(MinCost(arr, N));
}
static int MinCost( int [] arr, int n)
{
List< int > frequencies = new List< int >();
int leftEnd = 1;
int count = 1;
int prev = arr[0];
while (leftEnd < n) {
if (prev == arr[leftEnd]) {
count++;
}
else {
frequencies.Add(count);
count = 1;
prev = arr[leftEnd];
}
leftEnd++;
}
frequencies.Add(count);
frequencies.Sort();
if (frequencies.Count == 1) {
return 0;
}
else {
int median = frequencies[frequencies.Count / 2];
int operations = 0;
for ( int i = 0; i < frequencies.Count; i++) {
operations
+= Math.Abs(frequencies[i] - median);
}
return operations;
}
}
}
|
Javascript
function MinCost(arr, n)
{
let frequencies=[];
let leftEnd = 1;
let count = 1;
let prev = arr[0];
while (leftEnd < n) {
if (prev == arr[leftEnd]) {
count++;
}
else {
frequencies.push(count);
count = 1;
prev = arr[leftEnd];
}
leftEnd++;
}
frequencies.push(count);
frequencies.sort();
if (frequencies.length == 1) {
return 0;
}
else {
let median = frequencies[frequencies.length / 2];
let operations = 0;
for (let i = 0; i < frequencies.length; i++) {
operations += Math.abs(frequencies[i] - median);
}
return operations;
}
}
let N = 8;
let arr = [5, 5, 5, 6, 2, 2, 5, 5 ];
console.log((MinCost(arr, N)));
|
Time Complexity: O(N*logN)
Auxiliary Space: O(N)
Another Approach:
- Sort the input array arr[].
- Initialize two pointers i and j to the beginning of the array.
- Traverse the array with the pointers i and j such that i <= j < n, where n is the length of the array.
- If arr[i] is equal to arr[j], increment j. Otherwise, calculate the frequency of arr[i] as j – i and store it in a variable freq. Increment i to j and set j to i+1.
- Store the frequency freq in a vector frequencies.
- After the loop, if the value of i is less than n, then the last element in the array has a frequency of n – i. Store this frequency in frequencies as well.
- Sort the vector frequencies.
- Calculate the median as frequencies[frequencies.size()/2].
- Calculate the sum of absolute differences of all frequencies in the vector frequencies from the median. This sum is the minimum number of
- operations required to make consecutive occurrences of all elements equal.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int MinCost( int arr[], int n)
{
sort(arr, arr + n);
int i = 0, j = 0;
vector< int > frequencies;
while (i < n && j < n) {
if (arr[i] == arr[j]) {
j++;
}
else {
int freq = j - i;
frequencies.push_back(freq);
i = j;
j++;
}
}
int freq = n - i;
frequencies.push_back(freq);
sort(frequencies.begin(), frequencies.end());
if (frequencies.size() == 1) {
return 0;
}
else {
int median = frequencies[frequencies.size() / 2];
int operations = 0;
for ( int i = 0; i < frequencies.size(); i++) {
operations += abs (frequencies[i] - median);
}
return operations;
}
}
int main()
{
int N = 8;
int arr[] = { 5, 5, 5, 6, 2, 2, 5, 5 };
cout << (MinCost(arr, N));
}
|
Java
import java.util.*;
public class GFG {
public static int MinCost( int [] arr, int n)
{
Arrays.sort(arr);
int i = 0 , j = 0 ;
ArrayList<Integer> frequencies = new ArrayList<>();
while (i < n && j < n) {
if (arr[i] == arr[j]) {
j++;
}
else {
int freq = j - i;
frequencies.add(freq);
i = j;
j++;
}
}
int freq = n - i;
frequencies.add(freq);
Collections.sort(frequencies);
if (frequencies.size() == 1 ) {
return 0 ;
}
else {
int median = frequencies.get(frequencies.size() / 2 );
int operations = 0 ;
for ( int k = 0 ; k < frequencies.size(); k++) {
operations += Math.abs(frequencies.get(k) - median);
}
return operations;
}
}
public static void main(String[] args)
{
int N = 8 ;
int [] arr = { 5 , 5 , 5 , 6 , 2 , 2 , 5 , 5 };
System.out.println(MinCost(arr, N));
}
}
|
Python3
from typing import List
def MinCost(arr: List [ int ], n: int ) - > int :
arr.sort()
i, j = 0 , 0
frequencies = []
while i < n and j < n:
if arr[i] = = arr[j]:
j + = 1
else :
freq = j - i
frequencies.append(freq)
i = j
j + = 1
freq = n - i
frequencies.append(freq)
frequencies.sort()
if len (frequencies) = = 1 :
return 0
else :
median = frequencies[ len (frequencies) / / 2 ]
operations = 0
for freq in frequencies:
operations + = abs (freq - median)
return operations
arr = [ 5 , 5 , 5 , 6 , 2 , 2 , 5 , 5 ]
N = len (arr)
print (MinCost(arr, N))
|
C#
using System;
using System.Linq;
class GFG {
static int MinCost( int [] arr, int n)
{
Array.Sort(arr);
int i = 0, j = 0;
int [] frequencies = new int [n];
while (i < n && j < n) {
if (arr[i] == arr[j]) {
j++;
}
else {
int freqn = j - i;
frequencies[i] = freqn;
i = j;
j++;
}
}
int freq = n - i;
frequencies[i] = freq;
frequencies
= frequencies.Where(x = > x != 0).ToArray();
Array.Sort(frequencies);
if (frequencies.Length == 1) {
return 0;
}
else {
int median
= frequencies[frequencies.Length / 2];
int operations = 0;
for ( int k = 0; k < frequencies.Length; k++) {
operations
+= Math.Abs(frequencies[k] - median);
}
return operations;
}
}
static void Main()
{
int N = 8;
int [] arr = { 5, 5, 5, 6, 2, 2, 5, 5 };
Console.WriteLine(MinCost(arr, N));
}
}
|
Javascript
function MinCost(arr){
arr.sort((a, b) => a - b);
let i = 0, j = 0;
let frequencies = [];
while (i < arr.length && j < arr.length) {
if (arr[i] === arr[j]) {
j++;
}
else {
let freq = j - i;
frequencies.push(freq);
i = j;
j++;
}
}
let freq = arr.length - i;
frequencies.push(freq);
frequencies.sort((a, b) => a - b);
if (frequencies.length === 1) {
return 0;
}
else {
let x = Math.floor(frequencies.length / 2);
let median = frequencies[x];
let operations = 0;
for (let i = 0; i < frequencies.length; i++) {
operations += Math.abs(frequencies[i] - median);
}
return operations;
}
}
let arr = [ 5, 5, 5, 6, 2, 2, 5, 5 ];
console.log(MinCost(arr));
|
Time Complexity: O(N*logN)
Auxiliary Space : O(N)
Related articles:
Last Updated :
10 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...