O(n) Stack Solution
Complexity
Time complexity: O(n) each element put into stack ≤ 2 times
Space complexity: O(n)
Code
# Complexity
- Time complexity: $O(n)$ each element put into stack $\le$ 2 times
- Space complexity: $O(n)$
# Code
```cpp
vector<int> secondGreaterElement(vector<int> &nums){
    vector<int> nge(nums.size(), -1); //stores index of 2nd-closest element > curr

    stack<pair<int, bool>> st; //bool used to store count of greater elements encountered
    for (int i = 0; i < nums.size(); ++i){
        stack<pair<int, bool>> curr; //stores affected elements of stack
        while (st.size() > 0 && nums[st.top().first] < nums[i]){ curr.push(st.top()); st.pop(); }

        st.push({i, 1});

        while (curr.size() > 0){
            if (curr.top().second == 1){ st.push({curr.top().first, 0}); } //1st time
            else { nge[curr.top().first] = nums[i]; } //2nd time
            curr.pop();
        }
    } 

    return nge;
}
```
['Array', 'Stack', 'Monotonic Stack', 'C++']