Simple solution step wise - 2 iterations of array - O(n)


  • 0
    C

    i am storing maxIndex - index of maximum value & traversing starting from its next element in a circular fashion., self-explanatory code

    public class Solution {
        public int[] nextGreaterElements(int[] nums) {
            if(nums == null || nums.length == 0){
                return nums;
            }
            int maxVal = Integer.MIN_VALUE;
            int maxIndex = -1;
            for(int i =0 ; i< nums.length; i++){
                maxVal = Math.max(maxVal , nums[i]);
                if( nums[i] == maxVal){
                    maxIndex = i;
                }
            }
            
            int[] max = new int[nums.length];
            Stack<Integer> st = new Stack<Integer>();
            int n = max.length;
            st.push((maxIndex+1)%n);
            int i, j =0;
            for( i = maxIndex+2; j<n-1 ; j++, i++){
                i%= n;
                while(!st.isEmpty() && nums[st.peek()] < nums[i]){
                    max [st.pop()] = nums[i];
                }
                st.push(i);
            }
            
            while(!st.isEmpty()){
                max[st.pop()] = -1;
            }
            return max;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.