Approach
Stack-based processing
For Next Greater Element IV, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- Push the current item with only the information later steps need.
Code notes
- 28 lines of C++ from the credited upstream file 2454.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
If each item is pushed and popped at most once, the stack work is linear.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> secondGreaterElement(vector<int>& nums) {4 vector<int> ans(nums.size(), -1);5 6 stack<int> prevStack;7 8 stack<int> currStack;9 10 for (int i = 0; i < nums.size(); ++i) {11 12 while (!prevStack.empty() && nums[prevStack.top()] < nums[i])13 ans[prevStack.top()] = nums[i], prevStack.pop();14 15 16 17 stack<int> decreasingIndices;18 while (!currStack.empty() && nums[currStack.top()] < nums[i])19 decreasingIndices.push(currStack.top()), currStack.pop();20 while (!decreasingIndices.empty())21 prevStack.push(decreasingIndices.top()), decreasingIndices.pop();22 currStack.push(i);23 }24 25 return ans;26 }27};28