</>CodexBash
Back to problems
Not started

The next bigger number to the right

Easy
2000 ms limit256 MB memoryStacks and queuesArrays

Stuck?

Show a hint

Keep a stack of positions that have not been answered yet. A new value answers every waiting position smaller than itself.

For every position, report the first number to its right that is larger than it. If there is no larger number to the right, report -1.

Worked example#

For [4, 5, 2, 25]:

positionvaluefirst larger to the rightanswer
0455
152525
222525
325nothing is larger-1

So the answer is [5, 25, 25, -1].

The idea#

The obvious approach looks right from each position until it finds something larger. That is a nested loop, and on a hundred thousand numbers that are already sorted downwards it does five billion comparisons.

The way out is to notice what the slow version keeps re-reading. Walk left to right and hold a stack of positions still waiting for an answer. When a new value arrives, it is the answer for every waiting position smaller than it, so pop those and fill them in. Then the new position waits its own turn.

Every position is pushed once and popped at most once, so the whole thing is one pass no matter how the numbers are arranged.

Notice the shape the stack holds: reading bottom to top, the values never increase. A stack kept in order like that is called monotonic, and once you see it here you will see it in stock spans, in histograms and in rainwater.

Constraints#

  • 1 <= n <= 100000
  • -1000000000 <= nums[i] <= 1000000000

Input

nums is a count then that many integers.

Output

A count is not printed. Print the answers, separated by spaces.

Examples

Input

4
4 5 2 25

Output

5 25 25 -1

Only 25 has nothing larger to its right.

Input

4
13 7 6 12

Output

-1 12 12 -1

7 and 6 both wait for 12, and 13 never finds anything larger.

Input

3
1 2 3

Output

2 3 -1

Rising numbers, so each is answered by its neighbour.

Something wrong with this problem? Report an issue

Ready to try it

Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.

Free, and it stays free. No card.