Given an array A[] of N integers, the task is to find the minimum number of operations to sort the array in non-decreasing order, by choosing an integer X and replacing all the occurrences of X in the array with 0.
Examples:
Input: N = 5, A[] = {2, 2, 1, 1, 3}
Output: 1
Explanation: We choose X = 2 and replace all the occurrences of 2 with 0. Now the array becomes {2, 2, 1, 1, 3} -> {0, 0, 1, 1, 3} , which is sorted in increasing order.Input: N = 4, A[] = {2, 4, 1, 2}
Output: 3
Approach: The problem can be solved easily with the help of a Map.
Observations:
There are 2 cases that need to be considered :
- Case 1: Same element occurs more than once non-contiguously
- Consider the array : {1,6,3,4,5,3,2}.
- Now, since 3 at index 5 is greater than its next element, so we will make that 0 (as well as 3 at index 2).
- The array becomes {1,6,0,4,5,0,2}.
- So, the only way to sort the array would be to make all the elements before the zeroes equal to 0. i.e. the array becomes {0,0,0,0,0,0,2}.
- Case 2: Element at ith index is greater than the element at (i+1)th index :
- Consider the array : {1,2,3,5,4}.
- Since the element at the 3rd index is greater than the element at 4th index, we have to make the element at 3rd index equal to zero.
- So , the array becomes {1,2,3,0,4}.
- Now, the only way to sort the array would be to make all the elements before the zero equal to 0. i.e. the array becomes {0,0,0,0,4}.
It can be observed that in the end Case 2 breaks down to Case 1.
Considering the above cases, the problem can be solved following the below steps :
- Declare a hash map and add the frequency of each element of the array into the map.
- Iterate through the array from the back, i.e. from i=N-1 to i=0.
- At each iteration, handle Cases 1 and 2 as explained above.
- If iteration completes, return 0.
Below is the implementation of this approach:
// C++ code based on the above approach #include <bits/stdc++.h> using namespace std;
// Function to find minimum replacements // with 0 to sort the array int minimumReplacements( int A[], int N)
{ // Declaring a map
map< int , int > mp;
// Filling frequency of each element
// of array into map
for ( int i = 0; i < N; i++) {
mp[A[i]]++;
}
// Traversing through the array
for ( int i = N - 1; i >= 0; i--) {
// Handling consecutive
// equal elements
while (i > 0 && A[i] == A[i - 1]) {
mp[A[i]]--;
i--;
}
mp[A[i]]--;
// If frequency of the element
// becomes 0 erase it from the map
if (mp[A[i]] == 0) {
mp.erase(A[i]);
}
// Handling Case 1
if (mp.find(A[i]) != mp.end()) {
return mp.size();
}
// Handling Case 2
if (i > 0 && A[i - 1] > A[i]) {
return mp.size();
}
}
// If iteration completed, that means
// array was already sorted
return 0;
} // Driver code int main()
{ int N = 5;
int A[] = { 2, 2, 1, 1, 3 };
// Function Call
int answer = minimumReplacements(A, N);
cout << answer;
} |
// Java code based on the above approach import java.io.*;
import java.util.*;
class GFG {
// Function to find minimum replacements
// with 0 to sort the array
public static int minimumReplacements( int A[], int N)
{
// Declaring a map
TreeMap<Integer, Integer> mp =
new TreeMap<Integer, Integer>();
// Filling frequency of each element
// of array into map
for ( int i = 0 ; i < N; i++) {
if (mp.get(A[i])!= null )
mp.put(A[i],mp.get(A[i])+ 1 );
else
mp.put(A[i], 1 );
}
// Traversing through the array
for ( int i = N - 1 ; i >= 0 ; i--) {
// Handling consecutive
// equal elements
while (i > 0 && A[i] == A[i - 1 ]) {
mp.put(A[i],mp.get(A[i])- 1 );
i--;
}
mp.put(A[i],mp.get(A[i])- 1 );
// If frequency of the element
// becomes 0 erase it from the map
if (mp.get(A[i]) == 0 ) {
mp.remove(A[i]);
}
// Handling Case 1
if (mp.get(A[i]) != null ) {
return mp.size();
}
// Handling Case 2
if (i > 0 && A[i - 1 ] > A[i]) {
return mp.size();
}
}
// If iteration completed, that means
// array was already sorted
return 0 ;
}
// Driver Code
public static void main (String[] args) {
int N = 5 ;
int A[] = { 2 , 2 , 1 , 1 , 3 };
// Function Call
int answer = minimumReplacements(A, N);
System.out.println(answer);
}
} // This code is contributed by Rohit Pradhan |
# Python3 code based on the above approach # Function to find minimum replacements # with 0 to sort the array def minimumReplacements(A, N):
# Declaring a map
mp = dict .fromkeys(A, 0 );
# Filling frequency of each element
# of array into map
for i in range (N) :
if A[i] in mp :
mp[A[i]] + = 1 ;
else :
mp[A[i]] = 1
# Traversing through the array
for i in range (N - 1 , - 1 , - 1 ) :
# Handling consecutive
# equal elements
while (i > 0 and A[i] = = A[i - 1 ]) :
mp[A[i]] - = 1 ;
i - = 1 ;
mp[A[i]] - = 1 ;
# If frequency of the element
# becomes 0 erase it from the map
if (mp[A[i]] = = 0 ) :
mp.pop(A[i]);
# Handling Case 1
if A[i] in mp :
return len (mp);
# Handling Case 2
if (i > 0 and A[i - 1 ] > A[i]) :
return len (mp);
# If iteration completed, that means
# array was already sorted
return 0 ;
# Driver code if __name__ = = "__main__" :
N = 5 ;
A = [ 2 , 2 , 1 , 1 , 3 ];
# Function Call
answer = minimumReplacements(A, N);
print (answer);
# This code is contributed by AnkThon
|
// C# code based on the above approach using System;
using System.Collections.Generic;
using System.Linq;
class Program
{ // Driver Code
static void Main( string [] args)
{
int N = 5;
int [] A = { 2, 2, 1, 1, 3 };
// Function Call
int answer = minimumReplacements(A, N);
Console.WriteLine(answer);
}
// Function to find minimum replacements
// with 0 to sort the array
static int minimumReplacements( int [] A, int N)
{
// Declaring a sorted dictionary
SortedDictionary< int , int > mp
= new SortedDictionary< int , int >();
// Filling frequency of each element
// of array into mp
for ( int i = 0; i < N; i++) {
if (mp.ContainsKey(A[i]))
mp[A[i]] += 1;
else
mp[A[i]] = 1;
}
// Traversing through the array
for ( int i = N - 1; i >= 0; i--) {
// Handling consecutive
// equal elements
while (i > 0 && A[i] == A[i - 1]) {
mp[A[i]] -= 1;
i--;
}
mp[A[i]] -= 1;
// If frequency of the element
// becomes 0 erase it from the map
if (mp[A[i]] == 0) {
mp.Remove(A[i]);
}
// Handling Case 1
if (mp.ContainsKey(A[i])) {
return mp.Count();
}
// Handling Case 2
if (i > 0 && A[i - 1] > A[i]) {
return mp.Count();
}
}
// If iteration completed, that means
// array was already sorted
return 0;
}
} // This code is contributed by Tapesh (tapeshdua420) |
<script> // Javascript code based on the above approach // Function to find minimum replacements // with 0 to sort the array function minimumReplacements(A, N) {
// Declaring a map
let mp = new Map();
// Filling frequency of each element
// of array into map
for (let i = 0; i < N; i++) {
if (mp.get(A[i]) != null )
mp.set(A[i], mp.get(A[i]) + 1);
else
mp.set(A[i], 1);
}
// Traversing through the array
for (let i = N - 1; i >= 0; i--) {
// Handling consecutive
// equal elements
while (i > 0 && A[i] == A[i - 1]) {
mp.set(A[i], mp.get(A[i]) - 1);
i--;
}
mp.set(A[i], mp.get(A[i]) - 1);
// If frequency of the element
// becomes 0 erase it from the map
if (mp.get(A[i]) == 0) {
mp. delete (A[i]);
}
// Handling Case 1
if (mp.get(A[i]) != null ) {
return mp.size;
}
// Handling Case 2
if (i > 0 && A[i - 1] > A[i]) {
return mp.size;
}
}
// If iteration completed, that means
// array was already sorted
return 0;
} // Driver Code let N = 5; let A = [2, 2, 1, 1, 3]; // Function Call let answer = minimumReplacements(A, N); document.write(answer); // This code is contributed by Saurabh Jaiswal </script> |
1
Time Complexity: O(N)
Auxiliary Space: O(N)