Maintain a decreasing stack of indices to find each element's next greater neighbor in one pass.
About this algorithm
For each value in an array, find the first value to its right that is bigger, or -1 if there is none. A monotonic stack does it in one pass by keeping the positions that are still waiting for an answer, with their values going down from bottom to top. When a bigger value arrives, it answers everyone on the stack that is smaller than it.
Reach for a monotonic stack whenever each element needs its nearest bigger or smaller neighbour: daily temperatures (how many days until a warmer one), stock span, the largest rectangle in a histogram, and trapping rain water. The plain approach checks every later value for each element and takes O(n²) time. The stack brings that to O(n) because once an element gets its answer it is popped and never looked at again. The basic stack page covers push and pop on their own, and the balanced parentheses page uses a stack to match pairs rather than to compare sizes.
Fill a result array with -1 and start with an empty stack. The stack holds indices, so you can write the answer into the right slot later.
For each index i, while the stack is not empty and the value at the top index is smaller than arr[i], pop that index and set its result to arr[i]. The new value is the first bigger one those elements have seen.
When the top is no longer smaller (or the stack is empty), push i. It now waits for its own bigger value. Because smaller values were just removed, the values on the stack never go up from bottom to top.
Anything still on the stack at the end never found a bigger value to its right, so its -1 stays.
This is the array the page loads. 2 is pushed, then 1 (it is not bigger than 2, so nothing resolves). 5 pops 1 and then 2, so both get 5, and 5 is pushed. 3 waits on top of 5. 6 pops 3 and 5, giving each 6. 4 and then 1 wait on top of 6. 7 pops 1, 4 and 6, giving all three 7, and then 7 waits alone. The array ends, so 7 keeps -1. Result: [5, 5, 6, 6, 7, 7, 7, -1]. There were 8 pushes and 7 pops, never more than one of each per element.
The test is strictly smaller, so an equal value does not count as "greater" and waits on the stack. Change it to smaller or equal if your problem treats equal as greater. Flip the comparison to find the next smaller element instead.
Time: each index is pushed once and popped at most once, so the inner while loop runs at most n times over the whole pass. Space: a strictly falling array, such as 5, 4, 3, 2, 1, never pops, so all n indices sit on the stack at once; the result array is n as well.