Next Greater Element II

Practice this coding question on Coding Gurukul.

Problem statement

Inspection stations form a circular route. Each station displays an integer measurement, and an inspector starting at a station walks forward looking for the first strictly larger measurement. Passing the final station returns the inspector to the first one; the search ends before revisiting the starting station. Your task For every position in the array, print the value at the first later position with a strictly greater value in circular traversal order. Inspect at most the other n-1 positions. If no such position exists, print -1. Return values, not indices, and keep answers in the original station order. Equal measurements do not qualify. Negative measurements follow the same comparison rule. A single station therefore has answer -1. Aim for O(n) total time using a monotonic stack instead of starting a separate full walk at every station. Worked example For [4, 1, 3], station 4 has no greater measurement. Station 1 first encounters 3. Station 3 wraps around and encounters 4. Print -1 3 4.

Input format

First line: n. Second line: n integers.

Output format

Print n space-separated next-greater values, using -1 when absent.

Constraints

1 <= n <= 10000; -10^9 <= each value <= 10^9.

Sample input

3
4 1 3

Sample output

-1 3 4

Sign in to run or submit a solution in C++, Java or Python.

Loading Coding Gurukul…