Smallest subarray such that all elements are greater than K
Last Updated :
08 Sep, 2022
Given an array of N integers and a number K, the task is to find the length of the smallest subarray in which all the elements are greater than K. If there is no such subarray possible, then print -1.
Examples:
Input: a[] = {3, 4, 5, 6, 7, 2, 10, 11}, K = 5
Output: 1
The subarray is {10}
Input: a[] = {1, 2, 3}, K = 13
Output: -1
Approach: The task is to find the smallest subarray with all elements greater than K. Since smallest subarray can be of size 1. So, just check if there exists any element in the array greater than K. If yes then print “1” else print “-1”.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int smallestSubarray( int a[], int n, int x)
{
int count = 0, length = 0;
for ( int i = 0; i < n; i++) {
if (a[i] > x) {
return 1;
}
}
return -1;
}
int main()
{
int a[] = { 1, 22, 3 };
int n = sizeof (a) / sizeof (a[0]);
int k = 13;
cout << smallestSubarray(a, n, k);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int smallestSubarray( int a[], int n, int x)
{
int count = 0 , length = 0 ;
for ( int i = 0 ; i < n; i++) {
if (a[i] > x) {
return 1 ;
}
}
return - 1 ;
}
public static void main (String[] args) {
int a[] = { 1 , 22 , 3 };
int n = a.length;
int k = 13 ;
System.out.println(smallestSubarray(a, n, k));
}
}
|
Python3
def smallestSubarray(a, n, k):
for i in range (n):
if a[i] > k:
return 1
return - 1
a = [ 1 , 22 , 3 ]
n = len (a)
k = 13
print (smallestSubarray(a, n, k))
|
C#
using System;
class GFG
{
static int smallestSubarray( int []a,
int n, int x)
{
for ( int i = 0; i < n; i++)
{
if (a[i] > x)
{
return 1;
}
}
return -1;
}
static public void Main ()
{
int []a = { 1, 22, 3 };
int n = a.Length;
int k = 13;
Console.WriteLine(smallestSubarray(a, n, k));
}
}
|
PHP
<?php
function smallestSubarray( $a , $n , $x )
{
$count = 0;
$length = 0;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $a [ $i ] > $x )
{
return 1;
}
}
return -1;
}
$a = array ( 1, 22, 3 );
$n = sizeof( $a );
$k = 13;
echo smallestSubarray( $a , $n , $k );
?>
|
Javascript
<script>
function smallestSubarray(a, n, x)
{
let count = 0, length = 0;
for (let i = 0; i < n; i++) {
if (a[i] > x) {
return 1;
}
}
return -1;
}
let a = [1, 22, 3 ]
let n = a.length
let k = 13;
document.write(smallestSubarray(a, n, k));
</script>
|
Complexity Analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...