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

• Last Updated : 19 May, 2022

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

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 ` `using` `namespace` `std;`   `// Function to find the minimum operation` `// to sort the array` `int` `minOpsSortArray(vector<``int``>& arr, ``int` `N)` `{` `    ``vector > 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

 ``

Output

`2`

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

My Personal Notes arrow_drop_up
Related Articles