Next Greater Element II in C++


Suppose we have a circular array (the next element of the last element is the first element of the array), we have to display the Next Greater Number for every element. Here the Next Greater Number of a number x is the first greater number to its traversing-order next in the array, this means we could search circularly to find its next greater number. If it is not present, then it will be -1. So if the numbers are [1, 2, 1, 3, 2, 1], then output will be: [2,3,3,-1,3,2]

To solve this, we will follow these steps −

  • n := size of array
  • define one array called res, of size n, and fill this with -1, define one stack st
  • for i in range 0 to 2n
    • index := i mod n, x := nums[index]
    • while st is not empty and nums[top of stack] < x
      • res[top of stack] := x
      • delete the top element from the stack
    • insert index into the stack
  • return res

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<int> nextGreaterElements(vector<int>& nums) {
      int n = nums.size();
      vector <int> res(n, - 1);
      stack <int> st;
      for(int i = 0; i < 2 * n; i++){
         int idx = i % n;
         int x = nums[idx];
         while(!st.empty() && nums[st.top()] < x){
            res[st.top()] = x;
            st.pop();
         }
         st.push(idx);
      }
      return res;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,1,3,2,1};
   print_vector(ob.nextGreaterElements(v));
}

Input

[1,2,1,3,2,1]

Output

[2,3,3,-1,3,2]

Updated on: 29-Apr-2020

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements