All problems

Problem 388

Next Smaller Element

Medium · 20 pts · Array, Stack, Monotonic Stack

Problem

For every element of the array, find the first element to its right that is strictly smaller than it. Print -1 for elements that have no smaller element to their right. Checking every element to the right is O(N²); a monotonic stack does it in O(N): scan from left to right and, whenever the current value is smaller than the value at the top of the stack, it is the answer for that stacked element.

Input

First line: N. Second line: N integers.

Output

Print N values, separated by spaces.

Constraints

1 <= N <= 100000; 0 <= A[i] <= 1000000000

Example input

5
4 8 5 2 25

Example output

2 5 2 -1 -1

Explanation

For 4 8 5 2 25: after 4 the first smaller value is 2; after 8 it is 5; after 5 it is 2; after 2 and 25 there is nothing smaller, so they get -1.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Reverse a Sublist Next: Asteroid Collision