Given an Array of N integers, the task is to find for each array element the nearest smaller element to its left. If the smaller element does not present then print -1.
Ex:- [ 2, 5, 1, 4, 8, 3, 2, 5 ]
for 2 nearest smaller element to its left is not available so print -1
for 5 nearest smaller element to its left is 2 so print 2
for 1 nearest smaller element to its left is not available so print -1
for 4 nearest smaller element to its left is 1 so print 1
for 8 nearest smaller element to its left is 4 so print 4
for 3 nearest smaller element to its left is 1 so print 1
for 2 nearest smaller element to its left is 1 so print 1
for 5 nearest smaller element to its left is 2 so print 2
So the final answer will be -1 2 -1 1 4 1 1 2.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class NearestSmall{ public static void main(String []args){ int[] arr = { 1, 4, 8, 3, 2, 5 }; for(int i=0; i<arr.length; i++){ int j = i-1; while(j >= 0){ if(arr[j]<arr[i]){ System.out.print(arr[j]+" "); break; } j --; } if(j==-1) System.out.print("-1 "); } } } |
Python
arr = [ 1, 4, 8, 3, 2, 5 ] for i in range(0,len(arr)): j = i-1; while j>=0: if arr[j]<arr[i]: print(arr[j], end=" ") break j -= 1 if j==-1: print("-1", end=" ")