Skip to content
Related Articles
Open in App
Not now

Related Articles

Minimum replacements with 0 to sort the array

Improve Article
Save Article
Like Article
  • Last Updated : 21 Mar, 2023
Improve Article
Save Article
Like Article

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




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




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




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




// 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)


Javascript




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


Output

1

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

Efficient Approach : ( Using two pointers ) 

Approach steps : 

  • Initialize i and j to -1.
  • Traverse the array and find the maximum element and its frequency.
  • Traverse the array again and find the first and last occurrences of the maximum element using the pointers i and j.
  • Replace all occurrences of the maximum element between i and j with 0.
  • Return the frequency of the maximum element.

Implementation :

C++




// C++ program for the above approach
 
#include <iostream>
using namespace std;
 
// Function to find the minimum number of replacements with 0 to sort the array
int minReplacements(int n, int arr[]) {
    int max_elem = -1;
    int max_freq = 0;
    int i = -1; // Initialize first occurrence of maximum element to -1
    int j = -1; // Initialize last occurrence of maximum element to -1
 
    // Find the maximum element and its frequency
    for (int k = 0; k < n; k++) {
        if (arr[k] > max_elem) {
            max_elem = arr[k];
              // Reset the maximum frequency to 1
            max_freq = 1;
        } else if (arr[k] == max_elem) {
           // Increment the maximum frequency
            max_freq++;
        }
    }
 
    // Find the first and last occurrences of the maximum element
    for (int k = 0; k < n; k++) {
        if (arr[k] == max_elem) {
           // If this is the first occurrence of the maximum element
            if (i == -1) {
                i = k;
            }
            j = k;
        }
    }
 
    // Replace all occurrences of the maximum element between i and j with 0
    for (int k = i; k <= j; k++) {
           // If the current element is equal to the maximum element
        if (arr[k] == max_elem) {
            arr[k] = 0; // Replace it with 0
        }
    }
 
    return max_freq;
}
 
// driver code
int main() {
    int n = 5;
    int arr[] = {2, 2, 1, 1, 3};
 
    cout << minReplacements(n, arr) << endl;
    return 0;
}
 
// this code is contributed by bhardwajji


Python3




# Function to find the minimum number of replacements with 0 to sort the array
def min_replacements(n, arr):
    max_elem = -1
    max_freq = 0
    i = -1 # Initialize first occurrence of maximum element to -1
    j = -1 # Initialize last occurrence of maximum element to -1
 
    # Find the maximum element and its frequency
    for k in range(n):
        if arr[k] > max_elem:
            max_elem = arr[k]
            # Reset the maximum frequency to 1
            max_freq = 1
        elif arr[k] == max_elem:
            # Increment the maximum frequency
            max_freq += 1
 
    # Find the first and last occurrences of the maximum element
    for k in range(n):
        if arr[k] == max_elem:
            # If this is the first occurrence of the maximum element
            if i == -1:
                i = k
            j = k
 
    # Replace all occurrences of the maximum element between i and j with 0
    for k in range(i, j+1):
        # If the current element is equal to the maximum element
        if arr[k] == max_elem:
            arr[k] = 0 # Replace it with 0
 
    return max_freq
 
 
# Driver code
if __name__ == '__main__':
    n = 5
    arr = [2, 2, 1, 1, 3]
 
    print(min_replacements(n, arr))


Output

1

Time Complexity: O(N), where N is the size of the array
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!