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 1! Be sure to post your answers, queries etc in the comments!
Problem : Nearest Greatest Element to the Left in an Integer array: Given an array, print the Next Greater Element for every element. The Next greater Element for an element x is the first greater element on the left side of x in array. Elements for which no greater element exist, consider next greater element as -1.
Sample: int [] array= {1,5,2,4};
Output: -1 -1 5 5
Sample: int [] array= {1,5,2,4,9,7,10,3,29,12};
Output: -1 -1 5 5 -1 9 -1 10 -1 29
Solution:
View/ Download from Github: (LINK)
package stacks;
import java.util.Stack;
import java.util.Vector;
public class Nearest_greater_to_left {
public static Vector ngl(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= {1,5,2,4,9,7,10,3,29,12};
Vector v= ngl(array, array.length);
for(Object obj: v){
System.out.print(obj +" ");
}
}
}
Happy Learning!!