Hello! So I’m doing a 100 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 32: Problem 1! 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[]= {4,1,7,9,2,0,3,5,10,6};
Output: 1 0 2 2 0 -1 -1 -1 6 -1
Solution:
View/Download from Github : (LINK)
package stacks;
import java.util.Collections;
import java.util.Stack;
import java.util.Vector;
public class Nearest_smaller_from_right {
public static Vector nsr (int [] array, int length){
Vector v= new Vector();
Stack s= new Stack();
for(int i=length-1; i>=0; 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]);
}
Collections.reverse(v);
return v;
}
public static void main (String [] args){
int array[]= {4,1,7,9,2,0,3,5,10,6};
Vector v=nsr(array, array.length);
for(Object obj:v){
System.out.print(obj + " ");
}
}
}
Happy Learning!!