Length of smallest subarray required to be removed to make remaining elements consecutive
Given an array arr[] consisting of N integers, the task is to find the length of the smallest subarray required to be removed to make the remaining array elements consecutive.
Examples:
Input: arr[] = {1, 2, 3, 7, 5, 4, 5}
Output: 2
Explanation:
Removing the subarray {7, 5} from the array arr[] modifies the array to {1, 2, 3, 4, 5}, which makes all array elements consecutive. Therefore, the length of the subarray removed is 2, which is minimum.
Input: arr[] = {4, 5, 6, 8, 9, 10}
Output: 3
Naive Approach: The simplest approach to solve the given problem is to remove generate all possible subarrays of the array arr[] and for each of them, check if their removal makes the remaining array elements consecutive or not. After checking for all the subarrays, print the length of the minimum subarray obtained that satisfies the condition.
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
bool isConsecutive( int arr[], int i, int j)
{
sort(arr + i, arr + j + 1);
for ( int k = i + 1; k <= j; k++) {
if (arr[k] != arr[k - 1] + 1)
return false ;
}
return true ;
}
int shortestSubarray( int arr[], int n)
{
int minLen = n;
for ( int i = 0; i < n; i++) {
for ( int j = i; j < n; j++) {
int temp[n];
int k = 0;
for ( int l = 0; l < n; l++) {
if (l < i || l > j) {
temp[k++] = arr[l];
}
}
if (isConsecutive(temp, 0, k - 1)) {
minLen = min(minLen, j - i + 1);
}
}
}
return minLen;
}
int main()
{
int arr[] = { 1, 2, 3, 7, 5, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << shortestSubarray(arr, n) << endl;
return 0;
}
|
Java
import java.util.Arrays;
public class ShortestSubarray {
static boolean isConsecutive( int [] arr, int i, int j) {
Arrays.sort(arr, i, j + 1 );
for ( int k = i + 1 ; k <= j; k++) {
if (arr[k] != arr[k - 1 ] + 1 ) {
return false ;
}
}
return true ;
}
static int shortestSubarray( int [] arr) {
int n = arr.length;
int minLen = n;
for ( int i = 0 ; i < n; i++) {
for ( int j = i; j < n; j++) {
int [] temp = new int [n];
int k = 0 ;
for ( int l = 0 ; l < n; l++) {
if (l < i || l > j) {
temp[k++] = arr[l];
}
}
if (isConsecutive(temp, 0 , k - 1 )) {
minLen = Math.min(minLen, j - i + 1 );
}
}
}
return minLen;
}
public static void main(String[] args) {
int [] arr = { 1 , 2 , 3 , 7 , 5 , 4 , 5 };
System.out.println(shortestSubarray(arr));
}
}
|
Python3
def is_consecutive(arr, i, j):
arr[i:j + 1 ] = sorted (arr[i:j + 1 ])
for k in range (i + 1 , j + 1 ):
if arr[k] ! = arr[k - 1 ] + 1 :
return False
return True
def shortest_subarray(arr):
n = len (arr)
min_len = n
for i in range (n):
for j in range (i, n):
temp = [arr[l] for l in range (n) if l < i or l > j]
k = len (temp)
if is_consecutive(temp, 0 , k - 1 ):
min_len = min (min_len, j - i + 1 )
return min_len
if __name__ = = "__main__" :
arr = [ 1 , 2 , 3 , 7 , 5 , 4 , 5 ]
result = shortest_subarray(arr)
print (result)
|
C#
using System;
class SmallestSubarrayRemoval {
static bool IsConsecutive( int [] arr, int i, int j)
{
Array.Sort(arr, i, j - i + 1);
for ( int k = i + 1; k <= j; k++) {
if (arr[k] != arr[k - 1] + 1)
return false ;
}
return true ;
}
static int ShortestSubarray( int [] arr)
{
int n = arr.Length;
int minLen = n;
for ( int i = 0; i < n; i++) {
for ( int j = i; j < n; j++) {
int [] temp = new int [n];
int k = 0;
for ( int l = 0; l < n; l++) {
if (l < i || l > j) {
temp[k++] = arr[l];
}
}
if (IsConsecutive(temp, 0, k - 1)) {
minLen = Math.Min(minLen, j - i + 1);
}
}
}
return minLen;
}
static void Main( string [] args)
{
int [] arr = { 1, 2, 3, 7, 5, 4, 5 };
int result = ShortestSubarray(arr);
Console.WriteLine(result);
}
}
|
Javascript
function isConsecutive(arr, i, j) {
arr.slice(i, j + 1).sort();
for (let k = i + 1; k <= j; k++) {
if (arr[k] !== arr[k - 1] + 1)
return false ;
}
return true ;
}
function shortestSubarray(arr, n) {
let minLen = n;
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
let temp = [];
let k = 0;
for (let l = 0; l < n; l++) {
if (l < i || l > j) {
temp[k++] = arr[l];
}
}
if (isConsecutive(temp, 0, k - 1)) {
minLen = Math.min(minLen, j - i + 1);
}
}
}
return minLen;
}
let arr = [1, 2, 3, 7, 5, 4, 5];
let n = arr.length;
console.log(shortestSubarray(arr, n));
|
Time Complexity: O(N3), where N is the size of the input array.
Auxiliary Space: O(N), as we are using an extra array of size N to store the subarray.
Efficient Approach: The above approach can be optimized by storing the length of the longest prefix and suffix of consecutive elements and then find the minimum length of the subarray required to be removed such that the concatenation of the prefix and suffix forms a sequence of consecutive elements.
Follow the below steps to solve the problem:
- Initialize two variables, say L as 0 and R as (N – 1) to store the ending indices of the longest prefix and starting index of the longest suffix of consecutive elements respectively.
- Update the value of L to the first index where arr[i] + 1 is not equal to arr[i + 1] such that arr[0, …, L] is a consecutive prefix array.
- Update the value of R to the first index from the end where arr[i] is not equal to arr[i – 1] + 1 such that arr[R, …, N – 1] is a consecutive suffix array.
- Initialize a variable, say ans, to store the minimum of (N – L – 1) and R to store the required result.
- If the value of arr[R] ? arr[L] + 1, then store the right index, R1 as arr[0, …, L, R1, …, N – 1] is a consecutive array.
- If the value of (R1 – L – 1) is less than the value of ans, then update the value of ans to (R1 – L – 1).
- After completing the above steps, print the value of the ans as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void shortestSubarray( int * A, int N)
{
int i;
int left_index;
for (i = 0; i < N - 1; i++) {
if (A[i] + 1 != A[i + 1])
break ;
}
left_index = i;
int right_index;
for (i = N - 1; i >= 1; i--) {
if (A[i] != A[i - 1] + 1)
break ;
}
right_index = i;
int updated_right;
int minLength = min(N - left_index - 1,
right_index);
if (A[right_index]
<= A[left_index] + 1) {
updated_right = right_index
+ A[left_index]
- A[right_index] + 1;
if (updated_right < N)
minLength = min(minLength,
updated_right
- left_index - 1);
}
cout << minLength;
}
int main()
{
int arr[] = { 1, 2, 3, 7, 4, 3, 5 };
int N = sizeof (arr) / sizeof (arr[0]);
shortestSubarray(arr, N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG{
static void shortestSubarray( int A[], int N)
{
int i;
int left_index;
for (i = 0 ; i < N - 1 ; i++)
{
if (A[i] + 1 != A[i + 1 ])
break ;
}
left_index = i;
int right_index;
for (i = N - 1 ; i >= 1 ; i--)
{
if (A[i] != A[i - 1 ] + 1 )
break ;
}
right_index = i;
int updated_right;
int minLength = Math.min(N - left_index - 1 ,
right_index);
if (A[right_index] <= A[left_index] + 1 )
{
updated_right = right_index + A[left_index] -
A[right_index] + 1 ;
if (updated_right < N)
minLength = Math.min(minLength,
updated_right -
left_index - 1 );
}
System.out.println(minLength);
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 7 , 4 , 3 , 5 };
int N = arr.length;
shortestSubarray(arr, N);
}
}
|
Python3
def shortestSubarray(A, N):
i = 0
left_index = 0
for i in range (N - 1 ):
if (A[i] + 1 ! = A[i + 1 ]):
break
left_index = i
right_index = 0
i = N - 1
while (i > = 1 ):
if (A[i] ! = A[i - 1 ] + 1 ):
break
i - = 1
right_index = i
updated_right = 0
minLength = min (N - left_index - 1 , right_index)
if (A[right_index] < = A[left_index] + 1 ):
updated_right = (right_index + A[left_index] -
A[right_index] + 1 )
if (updated_right < N):
minLength = min (minLength, updated_right -
left_index - 1 )
print (minLength)
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 , 7 , 4 , 3 , 5 ]
N = len (arr)
shortestSubarray(arr, N)
|
C#
using System;
class GFG{
static void shortestSubarray( int [] A, int N)
{
int i;
int left_index;
for (i = 0; i < N - 1; i++)
{
if (A[i] + 1 != A[i + 1])
break ;
}
left_index = i;
int right_index;
for (i = N - 1; i >= 1; i--)
{
if (A[i] != A[i - 1] + 1)
break ;
}
right_index = i;
int updated_right;
int minLength = Math.Min(N - left_index - 1,
right_index);
if (A[right_index] <= A[left_index] + 1)
{
updated_right = right_index + A[left_index] -
A[right_index] + 1;
if (updated_right < N)
minLength = Math.Min(minLength,
updated_right -
left_index - 1);
}
Console.WriteLine(minLength);
}
static public void Main()
{
int [] arr = { 1, 2, 3, 7, 4, 3, 5 };
int N = arr.Length;
shortestSubarray(arr, N);
}
}
|
Javascript
<script>
function shortestSubarray(A, N)
{
let i;
let left_index;
for (i = 0; i < N - 1; i++)
{
if (A[i] + 1 != A[i + 1])
break ;
}
left_index = i;
let right_index;
for (i = N - 1; i >= 1; i--)
{
if (A[i] != A[i - 1] + 1)
break ;
}
right_index = i;
let updated_right;
let minLength = Math.min(N - left_index - 1,
right_index);
if (A[right_index] <= A[left_index] + 1)
{
updated_right = right_index + A[left_index] -
A[right_index] + 1;
if (updated_right < N)
minLength = Math.min(minLength,
updated_right -
left_index - 1);
}
document.write(minLength);
}
let arr = [ 1, 2, 3, 7, 4, 3, 5 ];
let N = arr.length;
shortestSubarray(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
09 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...