Given an array arr[] of length N, the task is to find the length of the longest subarray with smaller elements on the immediate left for each element in the given array.
Example:
Input: arr[] = { 2, 1, 7, 6, 7 }
Output: 0 0 2 0 1
Explanation:
Index 0 (2): No substring is present to the immediate left having all smaller elements. So, length=0
Index 1 (1): No substring is present to the immediate left having all smaller elements. So, length=0
Index 2 (7): Substring {2, 1} is present to the immediate left having all smaller elements. So, length=2
Index 3 (6): No substring is present to the immediate left having all smaller elements. So, length=0
Index 4 (2): Substring {6} is present to the immediate left having all smaller elements. So, length=1
Input: arr[] = { 4, 5, 7, 6, 10 }
Output: 0 1 2 0 4
Approach: For every element travel to its left until the element to the left is greater or the array ends to find the length of the longest subarray with smaller elements on the immediate left. Follow the below steps, to solve this problem:
- Traverse each element in array arr[].
- For each element run another loop in the left direction.
- Count all the elements smaller than the current element until a greater element comes or the array ends.
- Print the answer according to the above observation.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void subarrayLength( int * arr, int n)
{
for ( int i = 0; i < n; i++) {
int ans = 0;
for ( int j = i - 1; j >= 0; j--) {
if (arr[i] <= arr[j]) {
break ;
}
ans++;
}
cout << ans << " " ;
}
}
int main()
{
int n = 5;
int arr[n] = { 1, 4, 2, 6, 3 };
subarrayLength(arr, n);
return 0;
}
|
Java
class GFG{
static void subarrayLength( int arr[], int n)
{
for ( int i = 0 ; i < n; i++)
{
int ans = 0 ;
for ( int j = i - 1 ; j >= 0 ; j--)
{
if (arr[i] <= arr[j])
{
break ;
}
ans++;
}
System.out.print(ans + " " );
}
}
public static void main(String args[])
{
int n = 5 ;
int arr[] = { 1 , 4 , 2 , 6 , 3 };
subarrayLength(arr, n);
}
}
|
Python3
def subarrayLength(arr, n):
for i in range ( 0 , n):
ans = 0
for j in range (i - 1 , - 1 , - 1 ):
if (arr[i] < = arr[j]):
break
ans + = 1
print (ans, end = " " )
if __name__ = = "__main__" :
n = 5
arr = [ 1 , 4 , 2 , 6 , 3 ]
subarrayLength(arr, n)
|
C#
using System;
class GFG{
static void subarrayLength( int []arr, int n)
{
for ( int i = 0; i < n; i++)
{
int ans = 0;
for ( int j = i - 1; j >= 0; j--)
{
if (arr[i] <= arr[j])
{
break ;
}
ans++;
}
Console.Write(ans + " " );
}
}
public static void Main()
{
int n = 5;
int []arr = { 1, 4, 2, 6, 3 };
subarrayLength(arr, n);
}
}
|
Javascript
<script>
function subarrayLength(arr, n)
{
for (let i = 0; i < n; i++)
{
let ans = 0;
for (let j = i - 1; j >= 0; j--) {
if (arr[i] <= arr[j]) {
break ;
}
ans++;
}
document.write(ans + " " );
}
}
let n = 5;
let arr = [1, 4, 2, 6, 3];
subarrayLength(arr, n);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(1)