Next Greater Element II

Monotonic Stack & Queue Problems DSA practice problem on Onlearn.

Difficulty: medium.

Topics: Next Greater Element 2, Arrays, Stack, Loops, Time Complexity, Space Complexity, Optimization, complexity analysis, mathematical operations, array, monotonic stack, array traversal, Next/Previous Greater/Smaller Element, Algorithm Analysis.

Problem Statement Given a circular integer array nums, return the next greater element for every element. The next greater element of an element x is the first greater number to its traversing order in the array. If no greater number exists, output 1 for this number. A circular array means the elements wrap around. For example, if nums = [1,2,3,4,5], the next element after 5 is 1. Input Specification The input consists of a single line containing space separated integers nums[0], nums[1], ..., nums[n 1]. Output Specification Output a single line containing space separated integers, where the i th integer is the next greater element for nums[i]. Constraints 1 <= nums.length <= 10^4 10^9 <= nums[i] <= 10^9 Sample Test Cases Sample Input 1: 1 2 1 Sample Output 1: 2 1 2 Explanation 1: For the first 1, the next greater element is 2. For 2, there is no greater element in the array. For the second 1, we need to look circularly, and the next greater element is 2. Sample Input 2: 1 2 3 4 3 Sample Output 2: 2 3 4 1 4 Explanation 2: For 1, next greater is 2. For 2, next greater is 3. For 3 (first), next greater is 4. For 4, no greater element exists. For 3 (second), next greater (circularly) is 4.