CJCoding With Joseph
15free / daySign inCreate account

Next Greater Element

Write a function vector<int> nextGreater(const vector<int>& v) that returns a vector of the same length where position i holds the first element to the right of v[i] that is strictly greater than v[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
Topics:
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.