Next Greater Element - 2

Stack / Queues Monotonic Stack Medium

Given a circular integer array arr, return the next greater element for every element in arr.


The next greater element for an element x is the first element greater than x that we come across while traversing the array in a clockwise manner.


If it doesn't exist, return -1 for that element element.

Examples:

Input: arr = [3, 10, 4, 2, 1, 2, 6, 1, 7, 2, 9]

Output: [10, -1, 6, 6, 2, 6, 7, 7, 9, 9, 10]

Explanation: For the first element in arr i.e, 3, the greater element which comes next to it while traversing and is closest to it is 10. Hence,10 is present on index 0 in the resultant array. Now for the second element i.e, 10, there is no greater number and hence -1 is it’s next greater element (NGE). Similarly, we got the NGEs for all other elements present in arr.  

Input: arr = [5, 7, 1, 7, 6, 0]

Output: [7, -1, 7, -1, 7, 5]

Explanation: For the first element in arr i.e, 5, the greater element which comes next to it while traversing and is closest to it is 7. Now for the second element i.e, 7, there is no greater number and hence -1 is it’s next greater element (NGE). Similarly, we got the NGEs for all other elements present in arr.

Input: arr = [1, 2, 3, 4, 5]

Constraints

  •   1 ≤ n≤ 105
  •   0 ≤ arr[i] ≤ 109

Hints

  • Since the array is circular, we simulate two passes over the array by iterating twice (2n iterations). For every element.
  • For every element in the first pass, push it onto the stack, and during the second pass, process elements as if the array is extended. If an element finds a greater element in the first or second pass, update its NGE; otherwise, assign -1.

Company Tags

Micron Technology Freshworks Cerner Splunk Byju's Walmart Ubisoft Oracle MongoDB Reddit NVIDIA Pinterest Ernst & Young DoorDash HCL Technologies Epic Systems Stripe OYO Rooms KPMG Cloudflare Rakuten Western Digital Epic Games Bungie Flipkart Google Microsoft Amazon Meta Apple Netflix Adobe