Open In App

Minimum operations to sort Array by moving all occurrences of an element to start or end

Last Updated : 24 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N where arr[i] ≤ N, the task is to find the minimum number of operations to sort the array in increasing order where In one operation you can select an integer X and:

  • Move all the occurrences of X to the start or
  • Move all the occurrences of X to the end.

Examples:

Input: arr[] = {2, 1, 1, 2, 3, 1, 4, 3}, N = 8
Output: 2
Explanation:
First operation -> Select X = 1 and add all the 1 in front. 
The updated array arr[] = {1, 1, 1, 2, 2, 3, 4, 3}.
Second operation -> Select X= 4 and add all the 4 in end.
The updated array arr[ ]  = [1, 1, 1, 2, 2, 3, 3, 4]. 
Hence the array become sorted in two operations.

Input: arr[] = {1, 1, 2, 2}, N = 4
Output: 0
Explanation: The array is already sorted. Hence the answer is 0.

 

Approach: This problem can be solved using the greedy approach based on the following idea.

The idea to solve this problem is to find the longest subsequence of elements (considering all occurrences of an element) which will be in consecutive positions in sorted form. Then those elements need not to be moved anywhere else, and only moving the other elements will sort array in minimum steps.

Follow the illustration below for a better understanding:

Illustration:

For example arr[] = {2, 1, 1, 2, 3, 1, 4, 3}.

When the elements are sorted they will be {1, 1, 1, 2, 2, 3, 3, 4}. 
The longest subsequence in arr[] which are in consecutive positions as they will be in sorted array is {2, 2, 3, 3}.

So the remaining unique elements are {1, 4} only.
Minimum required operations are 2.

First operation:
        => Move all the 1s to the front of array.
        => The updated array arr[] = {1, 1, 1, 2, 2, 3, 4, 3}

Second operation:
        =>  Move 4 to the end of the array.
        => The updated array arr[] = {1, 1, 1, 2, 2, 3, 3, 4}

Follow the steps below to solve this problem based on the above idea:

  • Divide the elements into three categories.
    • The elements that we will move in front.
    • The elements that we will not move anywhere.
    • The elements that we will move in the end.
  • So to make the array sorted, these three conditions must satisfy.
    • All the elements of the first category must be smaller than the smallest element of the second category.
    • All the elements in the third category must be larger than the largest element of the second category.
    • If we remove all the elements of the first and third categories, the remaining array must be sorted in non-decreasing order.
  • So to minimize the total steps the elements in the second category must be maximum as seen from the above idea.
  • Store the first and last occurrence of each element.
  • Start iterating from i = N to 1 (consider i as an array element  and not as an index):
    • If its ending point is smaller than the starting index of the element just greater than it then increase the size of the subsequence.
    • If it is not then set it as the last and continue for the other elements.
  • The unique elements other than the ones in the longest subsequence is the required answer.

Below is the implementation of the above approach :

C++




// C++ code for above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum operation
// to sort the array
int minOpsSortArray(vector<int>& arr, int N)
{
    vector<vector<int> > O(N + 1,
                           vector<int>(2, N + 1));
 
    // Storing the first and the last occurrence
    // of each integer.
    for (int i = 0; i < N; ++i) {
        O[arr[i]][0] = min(O[arr[i]][0], i);
        O[arr[i]][1] = i;
    }
 
    int ans = 0, tot = 0;
    int last = N + 1, ctr = 0;
    for (int i = N; i > 0; i--) {
 
        // Checking if the integer 'i'
        // is present in the array or not.
        if (O[i][0] != N + 1) {
            ctr++;
 
            // Checking if the last occurrence
            // of integer 'i' comes before
            // the first occurrence of the
            // integer 'j' that is just greater
            // than integer 'i'.
            if (O[i][1] < last) {
                tot++;
                ans = max(ans, tot);
                last = O[i][0];
            }
            else {
                tot = 1;
                last = O[i][0];
            }
        }
    }
 
    // Total number of distinct integers -
    // maximum number of distinct integers
    // that we do not move.
    return ctr - ans;
}
 
// Driver code
int main()
{
    int N = 8;
    vector<int> arr = { 2, 1, 1, 2, 3, 1, 4, 3 };
 
    // Function call
    cout << minOpsSortArray(arr, N);
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
  // Function to find the minimum operation
  // to sort the array
  static int minOpsSortArray(int[] arr, int N)
  {
    int[][] O = new int[N + 1][N + 1];
    for (int i = 0; i < N+1; i++) {
      for (int j = 0; j < N+1; j++) {
        O[i][j]=N+1;
      }
    }
 
    // Storing the first and the last occurrence
    // of each integer.
    for (int i = 0; i < N; ++i) {
      O[arr[i]][0] = Math.min(O[arr[i]][0], i);
      O[arr[i]][1] = i;
    }
 
    int ans = 0, tot = 0;
    int last = N + 1, ctr = 0;
    for (int i = N; i > 0; i--) {
 
      // Checking if the integer 'i'
      // is present in the array or not.
      if (O[i][0] != N + 1) {
        ctr++;
 
        // Checking if the last occurrence
        // of integer 'i' comes before
        // the first occurrence of the
        // integer 'j' that is just greater
        // than integer 'i'.
        if (O[i][1] < last) {
          tot++;
          ans = Math.max(ans, tot);
          last = O[i][0];
        }
        else {
          tot = 1;
          last = O[i][0];
        }
      }
    }
 
    // Total number of distinct integers -
    // maximum number of distinct integers
    // that we do not move.
    return ctr - ans;
  }
 
  // Driver Code
  public static void main (String[] args) {
    int N = 8;
    int[] arr = { 2, 1, 1, 2, 3, 1, 4, 3 };
 
    // Function call
    System.out.print(minOpsSortArray(arr, N));
  }
}
 
// This code is contributed by code_hunt.


Python3




# Python3 code for the above approach
 
# Function to find the minimum operation
# to sort the array
def minOpsSortArray(arr, N):
    O = []
    for i in range(N + 1):
        O.append([N + 1, N + 1])
 
    # Storing the first and last
    # occurrence of each integer
    for i in range(N):
        O[arr[i]][0] = min(O[arr[i]][0], i)
        O[arr[i]][1] = i
 
    ans = 0
    tot = 0
    last = N + 1
    ctr = 0
    for i in range(N, 0, -1):
 
        # Checking if the integer 'i'
        # is present in the array or not
        if O[i][0] != N + 1:
            ctr += 1
 
            # Checking if the last occurrence
            # of integer 'i' comes before
            # the first occurrence of the
            # integer 'j' that is just greater
            # than integer 'i'
            if O[i][1] < last:
                tot += 1
                ans = max(ans, tot)
                last = O[i][0]
            else:
                tot = 1
                last = O[i][0]
 
    # total number of distinct integers
    # maximum number of distinct integers
    # that we do not move
    return ctr - ans
 
# Driver Code
N = 8
arr = [2, 1, 1, 2, 3, 1, 4, 3]
 
# Function Call
print(minOpsSortArray(arr, N))
 
# This code is contributed by phasing17


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to find the minimum operation
  // to sort the array
  static int minOpsSortArray(int[] arr, int N)
  {
    int[,] O = new int[N + 1, N + 1];
    for (int i = 0; i < N+1; i++) {
      for (int j = 0; j < N+1; j++) {
        O[i, j]=N+1;
      }
    }
 
    // Storing the first and the last occurrence
    // of each integer.
    for (int i = 0; i < N; ++i) {
      O[arr[i], 0] = Math.Min(O[arr[i], 0], i);
      O[arr[i], 1] = i;
    }
 
    int ans = 0, tot = 0;
    int last = N + 1, ctr = 0;
    for (int i = N; i > 0; i--) {
 
      // Checking if the integer 'i'
      // is present in the array or not.
      if (O[i, 0] != N + 1) {
        ctr++;
 
        // Checking if the last occurrence
        // of integer 'i' comes before
        // the first occurrence of the
        // integer 'j' that is just greater
        // than integer 'i'.
        if (O[i, 1] < last) {
          tot++;
          ans = Math.Max(ans, tot);
          last = O[i, 0];
        }
        else {
          tot = 1;
          last = O[i, 0];
        }
      }
    }
 
    // Total number of distinct integers -
    // maximum number of distinct integers
    // that we do not move.
    return ctr - ans;
  }
 
  // Driver Code
  public static void Main()
  {
    int N = 8;
    int[] arr = { 2, 1, 1, 2, 3, 1, 4, 3 };
 
    // Function call
    Console.Write(minOpsSortArray(arr, N));
  }
}
 
// This code is contributed by sanjoy_62.


Javascript




<script>
    // JavaScript code for above approach
 
    // Function to find the minimum operation
    // to sort the array
    const minOpsSortArray = (arr, N) => {
        let O = new Array(N + 1).fill(0).map(() => new Array(2).fill(N + 1));
 
        // Storing the first and the last occurrence
        // of each integer.
        for (let i = 0; i < N; ++i) {
            O[arr[i]][0] = Math.min(O[arr[i]][0], i);
            O[arr[i]][1] = i;
        }
 
        let ans = 0, tot = 0;
        let last = N + 1, ctr = 0;
        for (let i = N; i > 0; i--) {
 
            // Checking if the integer 'i'
            // is present in the array or not.
            if (O[i][0] != N + 1) {
                ctr++;
 
                // Checking if the last occurrence
                // of integer 'i' comes before
                // the first occurrence of the
                // integer 'j' that is just greater
                // than integer 'i'.
                if (O[i][1] < last) {
                    tot++;
                    ans = Math.max(ans, tot);
                    last = O[i][0];
                }
                else {
                    tot = 1;
                    last = O[i][0];
                }
            }
        }
 
        // Total number of distinct integers -
        // maximum number of distinct integers
        // that we do not move.
        return ctr - ans;
    }
 
    // Driver code
    let N = 8;
    let arr = [2, 1, 1, 2, 3, 1, 4, 3];
 
    // Function call
    document.write(minOpsSortArray(arr, N));
 
// This code is contributed by rakeshsahni
 
</script>


Output

2

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

Efficient approach : Space optimization approach

In this approach we can improve the space complexity of the algorithm by using two variables to keep track of the minimum and maximum positions of the given element in the array instead of using a 2D vector O. This will reduce the space complexity from O(N) to O(1).  

Implementation steps : 

  • Declare function minOpsSortArray that takes a reference to a vector of integers arr and an integer N as arguments and returns an integer. 
  • Take variables minPos, maxPos, and ctr and Initialize variables to N+1, -1, and 0, respectively. 
  • Also take variables ans, tot, and last and Initialize variables to 0, 0, and N+1 respectively. 
  • Return the difference between ctr and ans.

Implementation : 

C++




// C++ program for above approach
#include <iostream>
#include <vector>
using namespace std;
 
// Function to find the minimum number of operations required to sort an array
int minOpsSortArray(vector<int>& arr, int N)
{
    // Initialize variables
    int minPos = N+1, maxPos = -1, ctr = 0;
    int ans = 0, tot = 0, last = N+1;
 
    // Iterate through array to update minPos, maxPos, and ctr
    for (int i = 0; i < N; i++) {
        if (arr[i] == arr[N-1]) {
            maxPos = i;
            ctr++;
        }
        if (arr[i] == arr[0]) {
            minPos = i;
            ctr++;
        }
    }
 
    // Iterate through array backwards to update ans, tot, last, minPos, and maxPos
    for (int i = N-2; i >= 0; i--) {
        if (arr[i] == arr[N-1]) {
            if (maxPos < last) {
                tot++;
                ans = max(ans, tot);
                last = minPos;
            } else {
                tot = 1;
                last = minPos;
            }
            maxPos = i;
        }
        if (arr[i] == arr[0]) {
            if (minPos < last) {
                tot++;
                ans = max(ans, tot);
                last = maxPos;
            } else {
                tot = 1;
                last = maxPos;
            }
            minPos = i;
        }
    }
 
    // Return the difference between ctr and ans
    return ctr - ans;
}
 
int main()
{
    int N = 8;
    vector<int> arr = { 2, 1, 1, 2, 3, 1, 4, 3 };
 
    // Function call
    cout << minOpsSortArray(arr, N) << endl;
 
    return 0;
}
 
// this code is contributed by bhardwajji


Python3




# Function to find the minimum number of operations required to sort an array
def minOpsSortArray(arr, N):
    # Initialize variables
    minPos = N+1
    maxPos = -1
    ctr = 0
    ans = 0
    tot = 0
    last = N+1
 
    # Iterate through array to update minPos, maxPos, and ctr
    for i in range(N):
        if arr[i] == arr[N-1]:
            maxPos = i
            ctr += 1
        if arr[i] == arr[0]:
            minPos = i
            ctr += 1
 
    # Iterate through array backwards to update ans, tot, last, minPos, and maxPos
    for i in range(N-2, -1, -1):
        if arr[i] == arr[N-1]:
            if maxPos < last:
                tot += 1
                ans = max(ans, tot)
                last = minPos
            else:
                tot = 1
                last = minPos
            maxPos = i
        if arr[i] == arr[0]:
            if minPos < last:
                tot += 1
                ans = max(ans, tot)
                last = maxPos
            else:
                tot = 1
                last = maxPos
            minPos = i
 
    # Return the difference between ctr and ans
    return ctr - ans
 
# Test the function
arr = [2, 1, 1, 2, 3, 1, 4, 3]
N = len(arr)
print(minOpsSortArray(arr, N))


Java




// Java program for above approach
 
import java.util.ArrayList;
 
public class GFG {
      // Function to find the minimum number of operations required to sort an array
    public static int minOpsSortArray(ArrayList<Integer> arr, int N) {
          // Initialize variables
        int minPos = N+1, maxPos = -1, ctr = 0;
        int ans = 0, tot = 0, last = N+1;
         
          // Iterate through array to update minPos, maxPos, and ctr
        for (int i = 0; i < N; i++) {
            if (arr.get(i) == arr.get(N-1)) {
                maxPos = i;
                ctr++;
            }
            if (arr.get(i) == arr.get(0)) {
                minPos = i;
                ctr++;
            }
        }
         
          // Iterate through array backwards to update ans, tot, last, minPos, and maxPos
        for (int i = N-2; i >= 0; i--) {
            if (arr.get(i) == arr.get(N-1)) {
                if (maxPos < last) {
                    tot++;
                    ans = Math.max(ans, tot);
                    last = minPos;
                } else {
                    tot = 1;
                    last = minPos;
                }
                maxPos = i;
            }
            if (arr.get(i) == arr.get(0)) {
                if (minPos < last) {
                    tot++;
                    ans = Math.max(ans, tot);
                    last = maxPos;
                } else {
                    tot = 1;
                    last = maxPos;
                }
                minPos = i;
            }
        }
             
          // Return the difference between ctr and ans
        return ctr - ans;
    }
     
      // Driver's code
    public static void main(String[] args) {
          // Input
        int N = 8;
        ArrayList<Integer> arr = new ArrayList<Integer>();
        arr.add(2); arr.add(1); arr.add(1); arr.add(2);
        arr.add(3); arr.add(1); arr.add(4); arr.add(3);
         
          // Function call
        System.out.println(minOpsSortArray(arr, N));
    }
}


C#




// C# program for above approach
 
using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG {
    // Function to find the minimum number of operations
    // required to sort an array
    static int MinOpsSortArray(List<int> arr, int N)
    {
        // Initialize variables
        int minPos = N + 1, maxPos = -1, ctr = 0;
        int ans = 0, tot = 0, last = N + 1;
        // Iterate through array to update minPos, maxPos,
        // and ctr
        for (int i = 0; i < N; i++) {
            if (arr[i] == arr[N - 1]) {
                maxPos = i;
                ctr++;
            }
            if (arr[i] == arr[0]) {
                minPos = i;
                ctr++;
            }
        }
 
        // Iterate through array backwards to update ans,
        // tot, last, minPos, and maxPos
        for (int i = N - 2; i >= 0; i--) {
            if (arr[i] == arr[N - 1]) {
                if (maxPos < last) {
                    tot++;
                    ans = Math.Max(ans, tot);
                    last = minPos;
                }
                else {
                    tot = 1;
                    last = minPos;
                }
                maxPos = i;
            }
            if (arr[i] == arr[0]) {
                if (minPos < last) {
                    tot++;
                    ans = Math.Max(ans, tot);
                    last = maxPos;
                }
                else {
                    tot = 1;
                    last = maxPos;
                }
                minPos = i;
            }
        }
 
        // Return the difference between ctr and ans
        return ctr - ans;
    }
 
      // Driver's Code
    static void Main() {
        int N = 8;
        List<int> arr
            = new List<int>{ 2, 1, 1, 2, 3, 1, 4, 3 };
 
        // Function call
        Console.WriteLine(MinOpsSortArray(arr, N));
    }
}


Javascript




// JavaScript program for above approach
function minOpsSortArray(arr, N) {
    // Initialize variables
    let minPos = N + 1,
        maxPos = -1,
        ctr = 0;
    let ans = 0,
        tot = 0,
        last = N + 1;
 
    // Iterate through array to update minPos, maxPos, and ctr
    for (let i = 0; i < N; i++) {
        if (arr[i] == arr[N - 1]) {
            maxPos = i;
            ctr++;
        }
        if (arr[i] == arr[0]) {
            minPos = i;
            ctr++;
        }
    }
 
    // Iterate through array backwards to update ans, tot, last, minPos, and maxPos
    for (let i = N - 2; i >= 0; i--) {
        if (arr[i] == arr[N - 1]) {
            if (maxPos < last) {
                tot++;
                ans = Math.max(ans, tot);
                last = minPos;
            } else {
                tot = 1;
                last = minPos;
            }
            maxPos = i;
        }
        if (arr[i] == arr[0]) {
            if (minPos < last) {
                tot++;
                ans = Math.max(ans, tot);
                last = maxPos;
            } else {
                tot = 1;
                last = maxPos;
            }
            minPos = i;
        }
    }
 
    // Return the difference between ctr and ans
    return ctr - ans;
}
 
// Driver's code
const N = 8;
const arr = [2, 1, 1, 2, 3, 1, 4, 3];
 
// Function call
console.log(minOpsSortArray(arr, N));


Output

2

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads