Hello! So I’m doing a 30 day coding challenge where I solve a few questions every day and thought of posting them here on my blog so that you guys can join the challenge too!
Welcome to Coding challenge Day 31: Problem 2! Be sure to post your answers, queries etc in the comments!
Problem : Nearest Smallest Element to the Left in an Integer array: Given an array, print the Next Smallest Element for every element. The Next smaller Element for an element x is the first smaller element on the left side of x in array. Elements for which no smaller element exist, consider next smaller element as -1.
Sample: int [] array= {2,5,1,8,9,4,10,0,7};
Output: -1 2 -1 1 8 1 4 -1 0
Sample: int [] array= {100, 130, 120, 90, 70, 80, 180};
Output: -1 100 100 -1 -1 70 80
Solution:
View/ Download from Github: (LINK)
package stacks;
import java.util.Stack;
import java.util.Vector;
public class Nearest_smaller_to_left {
public static Vector nsl (int [] array, int length){
Vector v= new Vector();
Stack s= new Stack();
for(int i=0; i<length; i++){
if(s.isEmpty()){
v.add(-1);
}
else if ((int)(s.peek())<array[i]){
v.add(s.peek());
}
else if ((int)(s.peek())>array[i]){
while(!s.isEmpty() && (int)(s.peek())>=array[i]){
s.pop();
}
if(s.isEmpty()){
v.add(-1);
} else {
v.add(s.peek());
}
}
s.push(array[i]);
}
return v;
}
public static void main (String [] args){
int [] array= {100, 130, 120, 90, 70, 80, 180};
Vector v= nsl(array, array.length);
for(Object obj: v){
System.out.print(obj+" ");
}
}
}
Happy Learning!!