[AlgoExpert] Next Greater Element

Next Greater Element

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <vector>
using namespace std;

vector<int> nextGreaterElement(vector<int> array) {
int n = array.size();
vector<int> st;
vector<int> res(n, INT_MIN);

for(int i = n - 1; i >= 0; i--) {
while(!st.empty() and st.back() <= array[i])
st.pop_back();
if(!st.empty())
res[i] = st.back();
st.push_back(array[i]);
}

for(int i = n - 1; i >= 0; i--) {
if(res[i] != INT_MIN) continue;
while(!st.empty() and st.back() <= array[i])
st.pop_back();
if(!st.empty())
res[i] = st.back();
else res[i] = -1;
}



return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/12/PS/AlgoExpert/next-greater-element/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.