Check if all array elements can be removed by the given operations
Last Updated :
24 May, 2021
Given an array arr[] containing distinct elements, the task is to check if all array elements can be removed by the selecting any two adjacent indices such that arr[i] < arr[i+1] and removing one of the two elements or both at each step. If it is possible, then print “Yes”. Otherwise, print “No”.
Examples:
Input: arr[] = {2, 8, 6, 1, 3, 5}
Output: Yes
Explanation:
Select arr[4] and arr[5]. Since 3 < 5, remove 3, thus modifying the array arr[] = {2, 8, 6, 1, 5}
Select arr[0] and arr[1]. Since 2 < 8, remove 8, thus modifying the array arr[] = {2, 6, 1, 5}
Select arr[0] and arr[1]. Since 2 < 6, remove both 2 and 6, thus modifying the array arr[] = {1, 5}
Select arr[0] and arr[1]. Since 1 < 5, remove both 1 and 5, thus modifying the array arr[] = {}
Input: arr[] = {6, 5, 1}
Output: NO
Naive Approach:
The idea is to consider all adjacent pairs from the given array and if it satisfies the given condition then remove one of those numbers and repeat this process till all the elements are removed. If it is possible then print “Yes”. Otherwise print “No”.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach:
As the elements of the array are distinct it can be observed that all elements of the array can be removed if the first element of the array is smaller than the last element of the array. Otherwise, all elements of the given array cannot be removed.
Follow the steps below to solve the problem:
- Check if arr[0] < arr[n – 1], print “Yes”.
- Otherwise, print “No”.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void removeAll( int arr[], int n)
{
if (arr[0] < arr[n - 1])
cout << "YES" ;
else
cout << "NO" ;
}
int main()
{
int Arr[] = { 10, 4, 7, 1, 3, 6 };
int size = sizeof (Arr) / sizeof (Arr[0]);
removeAll(Arr, size);
return 0;
}
|
Java
class GFG{
static void removeAll( int arr[], int n)
{
if (arr[ 0 ] < arr[n - 1 ])
System.out.print( "YES" );
else
System.out.print( "NO" );
}
public static void main(String[] args)
{
int Arr[] = { 10 , 4 , 7 , 1 , 3 , 6 };
int size = Arr.length;
removeAll(Arr, size);
}
}
|
Python3
def removeAll(arr, n):
if arr[ 0 ] < arr[n - 1 ]:
print ( "YES" )
else :
print ( "NO" )
arr = [ 10 , 4 , 7 , 1 , 3 , 6 ]
removeAll(arr, len (arr))
|
C#
using System;
class GFG{
static void removeAll( int []arr, int n)
{
if (arr[0] < arr[n - 1])
Console.Write( "YES" );
else
Console.Write( "NO" );
}
public static void Main(String[] args)
{
int []Arr = { 10, 4, 7, 1, 3, 6 };
int size = Arr.Length;
removeAll(Arr, size);
}
}
|
Javascript
<script>
function removeAll(arr,n)
{
if (arr[0] < arr[n - 1])
document.write( "YES" );
else
document.write( "NO" );
}
let Arr = [ 10, 4, 7, 1, 3, 6 ];
let size = Arr.length;
removeAll(Arr, size);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...