Coding Challenge Day-30: Problem 2: Nearest Greater to right

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 30: Problem 2! Be sure to post your answers, queries etc in the comments!

Problem : Nearest Greater to right: 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 right side of x in array. Elements for which no greater element exist, consider next greater element as -1.

Sample: int array[]={1,3,2,4}
Output: 3 3 4 -1

Sample input: int array[]= {4, 5, 2, 25}
Output: 5 25 25 -1

I referred to this (LINK) for solution and explanation.

Code:

View/Download on Github: (LINK)

package stacks;

import java.util.Collections;
import java.util.Stack;
import java.util.Vector;

public class Nearest_greater_to_right {
	
	public static Vector ngr (int array[], int size){
		Vector v= new Vector();
		Stack s= new Stack();
		
		for(int i=size-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 ((int)(s.peek())<=array[i] && !s.isEmpty()){
					s.pop();
				}
				if(!s.isEmpty()){
					v.add(s.peek());
				} else{
					v.add(array[i]);
				}
				
			}
			
			s.push(array[i]);
		}
		
		Collections.reverse(v);
		
		return v;
	}
	
	public static void main (String args[]){
		int [] array= {4, 5, 2, 25};
		Vector v= ngr(array, array.length);
		
		for(Object obj: v){
			System.out.print(obj+ " ");
		}
	}

}

Happy Learning!!

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close