← Back to STL Containers
Question 518
Next Greater Element
Next Greater Element
Write a functionvector<int> nextGreater(const vector<int>& v)that returns a vector of the same length where positioniholds the first element to the right ofv[i]that is strictly greater thanv[i], or -1 if no such element exists. Use a stack of indices. Example: for v = {4, 1, 5, 9, 2} the answer is {5, 5, 9, -1, -1}. The test prints the returned values separated by single spaces (see Expected Output). Do NOT write a main function.
Expected Output:
5 5 9 -1 -1 -1 -1 -1 2 3 -1
= newline. The output ends with a newline — print one after the last line.
Hints4 available
Sign in to use hintsTopics:
STL ContainersStacks
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)
Your Output
Run your code to see the output here...
Test Cases
Run your code to see test case results.