Minimum number of deletions to make a sorted sequence
Last Updated :
07 Nov, 2023
Given an array of n integers. The task is to remove or delete the minimum number of elements from the array so that when the remaining elements are placed in the same sequence order to form an increasing sorted sequence.
Examples :
Input : {5, 6, 1, 7, 4}
Output : 2
Removing 1 and 4
leaves the remaining sequence order as
5 6 7 which is a sorted sequence.
Input : {30, 40, 2, 5, 1, 7, 45, 50, 8}
Output : 4
A simple solution is to remove all subsequences one by one and check if remaining set of elements is in sorted order or not. The time complexity of this solution is exponential.
An efficient approach uses the concept of finding the length of the longest increasing subsequence of a given sequence.
Algorithm:
-->arr be the given array.
-->n number of elements in arr.
-->len be the length of longest
increasing subsequence in arr.
-->// minimum number of deletions
min = n - len
C++
#include <bits/stdc++.h>
using namespace std;
int lis( int arr[], int n )
{
int result = 0;
int lis[n];
for ( int i = 0; i < n; i++ )
lis[i] = 1;
for ( int i = 1; i < n; i++ )
for ( int j = 0; j < i; j++ )
if ( arr[i] > arr[j] &&
lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
for ( int i = 0; i < n; i++ )
if (result < lis[i])
result = lis[i];
return result;
}
int minimumNumberOfDeletions( int arr[],
int n)
{
int len = lis(arr, n);
return (n - len);
}
int main()
{
int arr[] = {30, 40, 2, 5, 1,
7, 45, 50, 8};
int n = sizeof (arr) / sizeof (arr[0]);
cout << "Minimum number of deletions = "
<< minimumNumberOfDeletions(arr, n);
return 0;
}
|
Java
class GFG
{
static int lis( int arr[], int n )
{
int result = 0 ;
int [] lis = new int [n];
for ( int i = 0 ; i < n; i++ )
lis[i] = 1 ;
for ( int i = 1 ; i < n; i++ )
for ( int j = 0 ; j < i; j++ )
if ( arr[i] > arr[j] &&
lis[i] < lis[j] + 1 )
lis[i] = lis[j] + 1 ;
for ( int i = 0 ; i < n; i++ )
if (result < lis[i])
result = lis[i];
return result;
}
static int minimumNumberOfDeletions( int arr[],
int n)
{
int len = lis(arr, n);
return (n - len);
}
public static void main (String[] args)
{
int arr[] = { 30 , 40 , 2 , 5 , 1 ,
7 , 45 , 50 , 8 };
int n = arr.length;
System.out.println( "Minimum number of" +
" deletions = " +
minimumNumberOfDeletions(arr, n));
}
}
|
Python3
def lis(arr, n):
result = 0
lis = [ 0 for i in range (n)]
for i in range (n):
lis[i] = 1
for i in range ( 1 , n):
for j in range (i):
if ( arr[i] > arr[j] and
lis[i] < lis[j] + 1 ):
lis[i] = lis[j] + 1
for i in range (n):
if (result < lis[i]):
result = lis[i]
return result
def minimumNumberOfDeletions(arr, n):
len = lis(arr, n)
return (n - len )
arr = [ 30 , 40 , 2 , 5 , 1 ,
7 , 45 , 50 , 8 ]
n = len (arr)
print ( "Minimum number of deletions = " ,
minimumNumberOfDeletions(arr, n))
|
C#
using System;
class GfG
{
static int lis( int []arr, int n )
{
int result = 0;
int [] lis = new int [n];
for ( int i = 0; i < n; i++ )
lis[i] = 1;
for ( int i = 1; i < n; i++ )
for ( int j = 0; j < i; j++ )
if ( arr[i] > arr[j] &&
lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
for ( int i = 0; i < n; i++ )
if (result < lis[i])
result = lis[i];
return result;
}
static int minimumNumberOfDeletions(
int []arr, int n)
{
int len = lis(arr, n);
return (n - len);
}
public static void Main (String[] args)
{
int []arr = {30, 40, 2, 5, 1,
7, 45, 50, 8};
int n = arr.Length;
Console.Write( "Minimum number of" +
" deletions = " +
minimumNumberOfDeletions(arr, n));
}
}
|
Javascript
<script>
function lis(arr,n)
{
let result = 0;
let lis= new Array(n);
for (let i = 0; i < n; i++ )
lis[i] = 1;
for (let i = 1; i < n; i++ )
for (let j = 0; j < i; j++ )
if ( arr[i] > arr[j] &&
lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
for (let i = 0; i < n; i++ )
if (result < lis[i])
result = lis[i];
return result;
}
function minimumNumberOfDeletions(arr,n)
{
let len = lis(arr,n);
return (n - len);
}
let arr = [30, 40, 2, 5, 1,7, 45, 50, 8];
let n = arr.length;
document.write( "Minimum number of deletions = "
+ minimumNumberOfDeletions(arr,n));
</script>
|
PHP
<?php
function lis( $arr , $n )
{
$result = 0;
$lis [ $n ] = 0;
for ( $i = 0; $i < $n ; $i ++ )
$lis [ $i ] = 1;
for ( $i = 1; $i < $n ; $i ++ )
for ( $j = 0; $j < $i ; $j ++ )
if ( $arr [ $i ] > $arr [ $j ] &&
$lis [ $i ] < $lis [ $j ] + 1)
$lis [ $i ] = $lis [ $j ] + 1;
for ( $i = 0; $i < $n ; $i ++ )
if ( $result < $lis [ $i ])
$result = $lis [ $i ];
return $result ;
}
function minimumNumberOfDeletions( $arr , $n )
{
$len = lis( $arr , $n );
return ( $n - $len );
}
$arr = array (30, 40, 2, 5, 1,
7, 45, 50, 8);
$n = sizeof( $arr ) / sizeof( $arr [0]);
echo "Minimum number of deletions = " ,
minimumNumberOfDeletions( $arr , $n );
?>
|
Output
Minimum number of deletions = 4
Time Complexity : O(n2)
Auxiliary Space: O(n)
Time Complexity can be decreased to O(nlogn) by finding the Longest Increasing Subsequence Size(N Log N)
This article is contributed by Ayush Jauhari.
Approach#2: Using longest increasing subsequence
One approach to solve this problem is to find the length of the longest increasing subsequence (LIS) of the given array and subtract it from the length of the array. The difference gives us the minimum number of deletions required to make the array sorted.
Algorithm
1. Calculate the length of the longest increasing subsequence (LIS) of the array.
2. Subtract the length of the LIS from the length of the array.
3. Return the difference obtained in step 2 as the output.
C++
#include <iostream>
#include <vector>
#include <algorithm> // Required for max_element
using namespace std;
int minDeletions(vector< int > arr) {
int n = arr.size();
vector< int > lis(n, 1);
for ( int i = 1; i < n; ++i) {
for ( int j = 0; j < i; ++j) {
if (arr[i] > arr[j]) {
lis[i] = max(lis[i], lis[j] + 1);
}
}
}
int maxLength = *max_element(lis.begin(), lis.end());
return n - maxLength;
}
int main() {
vector< int > arr = {5, 6, 1, 7, 4};
cout << minDeletions(arr) << endl;
return 0;
}
|
Java
import java.util.Arrays;
public class Main {
public static int minDeletions( int [] arr) {
int n = arr.length;
int [] lis = new int [n];
Arrays.fill(lis, 1 );
for ( int i = 1 ; i < n; i++) {
for ( int j = 0 ; j < i; j++) {
if (arr[i] > arr[j]) {
lis[i] = Math.max(lis[i], lis[j] + 1 );
}
}
}
return n - Arrays.stream(lis).max().getAsInt();
}
public static void main(String[] args) {
int [] arr = { 5 , 6 , 1 , 7 , 4 };
System.out.println(minDeletions(arr));
}
}
|
Python3
def min_deletions(arr):
n = len (arr)
lis = [ 1 ] * n
for i in range ( 1 , n):
for j in range (i):
if arr[i] > arr[j]:
lis[i] = max (lis[i], lis[j] + 1 )
return n - max (lis)
arr = [ 5 , 6 , 1 , 7 , 4 ]
print (min_deletions(arr))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
namespace MinDeletionsExample
{
class Program
{
static int MinDeletions(List< int > arr)
{
int n = arr.Count;
List< int > lis = Enumerable.Repeat(1, n).ToList();
for ( int i = 1; i < n; ++i)
{
for ( int j = 0; j < i; ++j)
{
if (arr[i] > arr[j])
{
lis[i] = Math.Max(lis[i], lis[j] + 1);
}
}
}
int maxLength = lis.Max();
return n - maxLength;
}
static void Main( string [] args)
{
List< int > arr = new List< int > { 5, 6, 1, 7, 4 };
Console.WriteLine(MinDeletions(arr));
Console.ReadKey();
}
}
}
|
Javascript
function minDeletions(arr) {
let n = arr.length;
let lis = new Array(n).fill(1);
for (let i = 1; i < n; i++) {
for (let j = 0; j < i; j++) {
if (arr[i] > arr[j]) {
lis[i] = Math.max(lis[i], lis[j] + 1);
}
}
}
return n - Math.max(...lis);
}
let arr = [5, 6, 1, 7, 4];
console.log(minDeletions(arr));
|
Time complexity: O(n^2), where n is length of array
Space complexity: O(n), where n is length of array
Approach#3: Using binary search
This approach uses binary search to find the correct position to insert a given element into the subsequence.
Algorithm
1. Initialize a list ‘sub’ with the first element of the input list.
2. For each subsequent element in the input list, if it is greater than the last element in ‘sub’, append it to ‘sub’.
3. Otherwise, use binary search to find the correct position to insert the element into ‘sub’.
4. The minimum number of deletions required is equal to the length of the input list minus the length of ‘sub’.
C++
#include <iostream>
#include <vector>
using namespace std;
int minDeletions(vector< int >& arr) {
int n = arr.size();
vector< int > sub;
sub.push_back(arr[0]);
for ( int i = 1; i < n; i++) {
if (arr[i] > sub.back()) {
sub.push_back(arr[i]);
} else {
int index = -1;
int val = arr[i];
int l = 0, r = sub.size() - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (sub[mid] >= val) {
index = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
if (index != -1) {
sub[index] = val;
}
}
}
return n - sub.size();
}
int main() {
vector< int > arr = {30, 40, 2, 5, 1, 7, 45, 50, 8};
int output = minDeletions(arr);
cout << output << endl;
return 0;
}
|
Java
import java.util.ArrayList;
public class Main {
static int minDeletions(ArrayList<Integer> arr) {
int n = arr.size();
ArrayList<Integer> sub = new ArrayList<>();
sub.add(arr.get( 0 ));
for ( int i = 1 ; i < n; i++) {
if (arr.get(i) > sub.get(sub.size() - 1 )) {
sub.add(arr.get(i));
} else {
int index = - 1 ;
int val = arr.get(i);
int l = 0 , r = sub.size() - 1 ;
while (l <= r) {
int mid = (l + r) / 2 ;
if (sub.get(mid) >= val) {
index = mid;
r = mid - 1 ;
} else {
l = mid + 1 ;
}
}
if (index != - 1 ) {
sub.set(index, val);
}
}
}
return n - sub.size();
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add( 30 );
arr.add( 40 );
arr.add( 2 );
arr.add( 5 );
arr.add( 1 );
arr.add( 7 );
arr.add( 45 );
arr.add( 50 );
arr.add( 8 );
int output = minDeletions(arr);
System.out.println(output);
}
}
|
Python3
def min_deletions(arr):
def ceil_index(sub, val):
l, r = 0 , len (sub) - 1
while l < = r:
mid = (l + r) / / 2
if sub[mid] > = val:
r = mid - 1
else :
l = mid + 1
return l
sub = [arr[ 0 ]]
for i in range ( 1 , len (arr)):
if arr[i] > sub[ - 1 ]:
sub.append(arr[i])
else :
sub[ceil_index(sub, arr[i])] = arr[i]
return len (arr) - len (sub)
arr = [ 30 , 40 , 2 , 5 , 1 , 7 , 45 , 50 , 8 ]
output = min_deletions(arr)
print (output)
|
C#
using System;
using System.Collections.Generic;
class Program
{
static int MinDeletions(List< int > arr)
{
int n = arr.Count;
List< int > sub = new List< int >();
sub.Add(arr[0]);
for ( int i = 1; i < n; i++)
{
if (arr[i] > sub[sub.Count - 1])
{
sub.Add(arr[i]);
}
else
{
int index = -1;
int val = arr[i];
int l = 0, r = sub.Count - 1;
while (l <= r)
{
int mid = (l + r) / 2;
if (sub[mid] >= val)
{
index = mid;
r = mid - 1;
}
else
{
l = mid + 1;
}
}
if (index != -1)
{
sub[index] = val;
}
}
}
return n - sub.Count;
}
static void Main()
{
List< int > arr = new List< int > { 30, 40, 2, 5, 1, 7, 45, 50, 8 };
int output = MinDeletions(arr);
Console.WriteLine(output);
Console.ReadLine();
}
}
|
Javascript
function minDeletions(arr) {
let n = arr.length;
let sub = [];
sub.push(arr[0]);
for (let i = 1; i < n; i++) {
if (arr[i] > sub[sub.length - 1]) {
sub.push(arr[i]);
} else {
let index = -1;
let val = arr[i];
let l = 0, r = sub.length - 1;
while (l <= r) {
let mid = Math.floor((l + r) / 2);
if (sub[mid] >= val) {
index = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
if (index !== -1) {
sub[index] = val;
}
}
}
return n - sub.length;
}
let arr = [30, 40, 2, 5, 1, 7, 45, 50, 8];
let output = minDeletions(arr);
console.log(output);
|
Time Complexity: O(n log n)
Auxiliary Space: O(n)
Similar Reads
Minimum number of subtract operation to make an array decreasing
You are given a sequence of numbers arr[0], arr[1], ..., arr[N - 1] and a positive integer K. In each operation, you may subtract K from any element of the array. You are required to find the minimum number of operations to make the given array decreasing. An array [Tex]arr[0], arr[1], ....., arr[N-
7 min read
Sort the elements by minimum number of operations
Given two positive integer arrays X[] and Y[] of size N, Where all elements of X[] are distinct. Considering all the elements of X[] are lying side by side initially on a line, the task is to find the minimum number of operations required such that elements in X[] becomes in increasing order where i
8 min read
Minimum number of deletions so that no two consecutive are same
Given a string, find minimum number of deletions required so that there will be no two consecutive repeating characters in the string. Examples: Input : AAABBB Output : 4 Explanation : New string should be AB Input : ABABABAB Output : 0 Explanation : There are no consecutive repeating characters. If
4 min read
Minimum deletions to make String S the Subsequence of any String in the Set D
Given a string S and a set of strings D, the task is to find the minimum number of deletions required to make the string S a subsequence of any string in the set D, such that the deletion can only be performed on the substring of S. Examples: Input: string S = "abcdefg", vector<string> D = {"a
13 min read
Minimum increment or decrement operations required to make the array sorted
Given an array arr[] of N integers, the task is to sort the array in non-decreasing order by performing the minimum number of operations. In a single operation, an element of the array can either be incremented or decremented by 1. Print the minimum number of operations required.Examples: Input: arr
15+ min read
Minimum number of strictly decreasing subsequences
Given an array arr[] of size N. The task is to split the array into minimum number of strictly decreasing subsequences. Calculate the minimum number of subsequences we can get by splitting. Examples: Input: N = 4, arr[] = {3, 5, 1, 2}Output: 2Explanation: We can split the array into two subsequences
7 min read
Minimum number of moves to make all elements equal
Given an array containing N elements and an integer K. It is allowed to perform the following operation any number of times on the given array: Insert the K-th element at the end of the array and delete the first element of the array. The task is to find the minimum number of moves needed to make al
7 min read
Minimum steps required to make an array decreasing
Given an array arr[], the task is to find the minimum steps required to make an array decreasing, where in each step remove all elements which are greater than elements on its left element.Examples: Input: arr[] = {3, 2, 1, 7, 5} Output: 2 Explanation: In the above array there are two steps required
12 min read
Minimum number of consecutive sequences that can be formed in an array
Given an array of integers. The task is to find the minimum number of consecutive sequences that can be formed using the elements of the array. Examples: Input: arr[] = { -3, -2, -1, 0, 2 } Output: 2 Consecutive sequences are (-3, -2, -1, 0), (2). Input: arr[] = { 3, 4, 0, 2, 6, 5, 10 } Output: 3 Co
4 min read
Find the minimum number of elements that should be removed to make an array good
Given an array of size N and an integer K. The array consists of only digits {0, 1, 2, 3, ...k-1}. The task is to make array good by removing some of the elements. The array of length x is called good if x is divisible by k and one can split the given array into x/k subsequences and each of form {0,
6 min read