Minimum operations to sort Array by moving all occurrences of an element to start or end
Last Updated :
23 Jul, 2025
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>
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));
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem