503. Next Greater Element II

1. Description

Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. 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, output -1 for this number.

2. Example

Example 1:
Input: [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.

3. Note

  • The length of given array won’t exceed 10000.

4. Solutions

4.1 Monotone Stack

n = i_words.size()
Time complexity: O(n)
Space complexity: O(n)

// Monotone Stack could be used to solve qustions about finding the next bigger or smaller value
class Solution {
public:
    vector<int> nextGreaterElements(const vector<int>& nums) {
        vector<int> result(nums.size(), -1);
        stack<int> increase_num_index;
        // when we find the next bigger number, we use an increase stack
        // increase stack means from the base to top, the stack is increasing
        // this structure could help us handle the decreasing subsequence quickly
        for(int i = 0; i < nums.size() * 2 - 1; ++i) {
            while(!increase_num_index.empty() && nums[increase_num_index.top()% nums.size()] < nums[i % nums.size()]) {
                result[increase_num_index.top()] = nums[i % nums.size()];
                increase_num_index.pop();
            }

            increase_num_index.push(i % nums.size());
        }

        return result;
    }
};
Last updated:
Tags: Stack
comments powered by Disqus