Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.
The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.
Example 1:
Input: nums = [1,2,1] Output: [2,-1,2] Explanation: The first 1's next greater number is 2; The number 2 can't find next greater number. The second 1's next greater number needs to search circularly, which is also 2.
Example 2:
Input: nums = [1,2,3,4,3] Output: [2,3,4,-1,4]
Constraints:
1 <= nums.length <= 104-109 <= nums[i] <= 109This approach utilizes a stack to keep track of the indices of the elements for which we are finding the next greater element. We traverse the array twice (length times two) to account for the circular nature of the array. For each element, we repeatedly pop elements from the stack while the current element is greater than the element represented by the index at the top of the stack. As we pop elements, we update their next greater element in the resulting array. The stack helps ensure that each element is processed efficiently, leading to an O(n) complexity.
This Python solution employs a stack to track the indices of elements. It processes each index twice using a modulo operation to simulate the circular nature of the array. It successfully finds the next greater element by leveraging the stack to keep track of indices that need to find a larger subsequent value.
C++
Java
JavaScript
C#
C
Time Complexity: O(n)
Space Complexity: O(n) (due to the stack and result array)
This approach uses two separate traversals to find the next greater element by checking for each element's greater counterpart. We double-iterate through the array copying elements to support cyclic checking. Though simpler conceptually, its efficiency isn't as optimal due to direct comparisons, and it could degrade to an O(n^2) complexity in worst cases. It's educational for understanding direct exhaustive search in circular constructs.
This Python solution performs direct iterative comparisons on pairs of elements. For each index, it tests succeeding elements using a nested loop construct, leveraging modulo to achieve wrap-around.
C++
Java
JavaScript
C#
C
Time Complexity: O(n^2) in the worst case
| Approach | Complexity |
|---|---|
| Approach 1: Using a Monotonic Stack | Time Complexity: |
| Approach 2: Double Traversal Without Stack | Time Complexity: |
Next Greater Element | Two Variants | Leetcode • take U forward • 265,567 views views
Watch 9 more video solutions →Practice Next Greater Element II with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor