Pages

Wednesday, September 24, 2025

next Greater element - Stack problem (V.V.imp)

 import java.util.*;


public class Classroom {

    public static void main(String[] args) {

        int arr[] = {6, 8, 0, 1, 3};

        Stack<Integer> s = new Stack<>();

        int nextGreater[] = new int[arr.length];

        

        for(int i = arr.length - 1; i >= 0; i--) {

            // 1 while

            while(!s.isEmpty() && arr[s.peek()] <= arr[i]) {

                s.pop();

            }

            // 2 if-else

            if(s.isEmpty()) {

                nextGreater[i] = -1;

            } else {

                nextGreater[i] = arr[s.peek()];

            }

            // 3 push in s

            s.push(i);

        }


        // Print result

        for(int i = 0; i < nextGreater.length; i++) {

            System.out.println(nextGreater[i] + " ");

        }

        System.out.println();

        

        // nextGreater Right

        // nextGreater Left

        // next Smaller right

        // next Smaller left

    }

}


OUTPUT:
-1 
-1 

No comments:

Post a Comment

remove duplicates from sorted array - two pointer approach (leetcode)

  class Solution {     public int removeDuplicates ( int [] nums ) {         // base case: return if array have no el.         if ( nums...