Minimum operations to sort Array by moving all occurrences of an element to start or end
Last Updated :
24 Apr, 2023
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++
#include <bits/stdc++.h>
using namespace std;
int minOpsSortArray(vector< int >& arr, int N)
{
vector<vector< int > > O(N + 1,
vector< int >(2, N + 1));
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--) {
if (O[i][0] != N + 1) {
ctr++;
if (O[i][1] < last) {
tot++;
ans = max(ans, tot);
last = O[i][0];
}
else {
tot = 1;
last = O[i][0];
}
}
}
return ctr - ans;
}
int main()
{
int N = 8;
vector< int > arr = { 2, 1, 1, 2, 3, 1, 4, 3 };
cout << minOpsSortArray(arr, N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
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 ;
}
}
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--) {
if (O[i][ 0 ] != N + 1 ) {
ctr++;
if (O[i][ 1 ] < last) {
tot++;
ans = Math.max(ans, tot);
last = O[i][ 0 ];
}
else {
tot = 1 ;
last = O[i][ 0 ];
}
}
}
return ctr - ans;
}
public static void main (String[] args) {
int N = 8 ;
int [] arr = { 2 , 1 , 1 , 2 , 3 , 1 , 4 , 3 };
System.out.print(minOpsSortArray(arr, N));
}
}
|
Python3
def minOpsSortArray(arr, N):
O = []
for i in range (N + 1 ):
O.append([N + 1 , N + 1 ])
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 ):
if O[i][ 0 ] ! = N + 1 :
ctr + = 1
if O[i][ 1 ] < last:
tot + = 1
ans = max (ans, tot)
last = O[i][ 0 ]
else :
tot = 1
last = O[i][ 0 ]
return ctr - ans
N = 8
arr = [ 2 , 1 , 1 , 2 , 3 , 1 , 4 , 3 ]
print (minOpsSortArray(arr, N))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
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;
}
}
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--) {
if (O[i, 0] != N + 1) {
ctr++;
if (O[i, 1] < last) {
tot++;
ans = Math.Max(ans, tot);
last = O[i, 0];
}
else {
tot = 1;
last = O[i, 0];
}
}
}
return ctr - ans;
}
public static void Main()
{
int N = 8;
int [] arr = { 2, 1, 1, 2, 3, 1, 4, 3 };
Console.Write(minOpsSortArray(arr, N));
}
}
|
Javascript
<script>
const minOpsSortArray = (arr, N) => {
let O = new Array(N + 1).fill(0).map(() => new Array(2).fill(N + 1));
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--) {
if (O[i][0] != N + 1) {
ctr++;
if (O[i][1] < last) {
tot++;
ans = Math.max(ans, tot);
last = O[i][0];
}
else {
tot = 1;
last = O[i][0];
}
}
}
return ctr - ans;
}
let N = 8;
let arr = [2, 1, 1, 2, 3, 1, 4, 3];
document.write(minOpsSortArray(arr, N));
</script>
|
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++
#include <iostream>
#include <vector>
using namespace std;
int minOpsSortArray(vector< int >& arr, int N)
{
int minPos = N+1, maxPos = -1, ctr = 0;
int ans = 0, tot = 0, last = N+1;
for ( int i = 0; i < N; i++) {
if (arr[i] == arr[N-1]) {
maxPos = i;
ctr++;
}
if (arr[i] == arr[0]) {
minPos = i;
ctr++;
}
}
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 ctr - ans;
}
int main()
{
int N = 8;
vector< int > arr = { 2, 1, 1, 2, 3, 1, 4, 3 };
cout << minOpsSortArray(arr, N) << endl;
return 0;
}
|
Python3
def minOpsSortArray(arr, N):
minPos = N + 1
maxPos = - 1
ctr = 0
ans = 0
tot = 0
last = N + 1
for i in range (N):
if arr[i] = = arr[N - 1 ]:
maxPos = i
ctr + = 1
if arr[i] = = arr[ 0 ]:
minPos = i
ctr + = 1
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 ctr - ans
arr = [ 2 , 1 , 1 , 2 , 3 , 1 , 4 , 3 ]
N = len (arr)
print (minOpsSortArray(arr, N))
|
Java
import java.util.ArrayList;
public class GFG {
public static int minOpsSortArray(ArrayList<Integer> arr, int N) {
int minPos = N+ 1 , maxPos = - 1 , ctr = 0 ;
int ans = 0 , tot = 0 , last = N+ 1 ;
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++;
}
}
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 ctr - ans;
}
public static void main(String[] args) {
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 );
System.out.println(minOpsSortArray(arr, N));
}
}
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static int MinOpsSortArray(List< int > arr, int N)
{
int minPos = N + 1, maxPos = -1, ctr = 0;
int ans = 0, tot = 0, last = N + 1;
for ( int i = 0; i < N; i++) {
if (arr[i] == arr[N - 1]) {
maxPos = i;
ctr++;
}
if (arr[i] == arr[0]) {
minPos = i;
ctr++;
}
}
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 ctr - ans;
}
static void Main() {
int N = 8;
List< int > arr
= new List< int >{ 2, 1, 1, 2, 3, 1, 4, 3 };
Console.WriteLine(MinOpsSortArray(arr, N));
}
}
|
Javascript
function minOpsSortArray(arr, N) {
let minPos = N + 1,
maxPos = -1,
ctr = 0;
let ans = 0,
tot = 0,
last = N + 1;
for (let i = 0; i < N; i++) {
if (arr[i] == arr[N - 1]) {
maxPos = i;
ctr++;
}
if (arr[i] == arr[0]) {
minPos = i;
ctr++;
}
}
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 ctr - ans;
}
const N = 8;
const arr = [2, 1, 1, 2, 3, 1, 4, 3];
console.log(minOpsSortArray(arr, N));
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...