A Game of Numbers
Practice
3.6 (175 votes)
Data structures
Easy
Stacks
Problem
83% Success 17966 Attempts 20 Points 1s Time Limit 256MB Memory 1024 KB Max Code

You are given an array A of N integers. Now, two functions \(F(X)\) and \(G(X)\) are defined:

\( F(X) \) : This is the smallest number Z such that \( X < Z \le N \) and \(A[X] < A[Z] \)

\( G(X) \) : This is the smallest number Z such that \( X < Z \le N \) and \(A[X] > A[Z] \)

Now, you need to find for each index i of this array \(G(F(i))\), where \( 1 \le i \le N \) . If such a number does not exist, for a particular index i, output 1 as its answer. If such a number does exist, output \(A[G(F(i))]\)

Input :

The first line contains a single integer N denoting the size of array A. Each of the next N lines contains a single integer, where the integer on the \(i^{th}\) line denotes \(A[i]\).

Output :

Print N space separated integers on a single line, where the \(i^{th}\) integer denotes \(A[G(F(i))]\) or 1, if \(G(F(i))\) does not exist.

Constraints:

\(1 \le N \le 30000 \)

\( 0 \le A[i] \le 10^{18} \)

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:20
53 votes
Tags:
Data StructuresDynamic programmingEasyStacks
Points:20
44 votes
Tags:
Data StructuresEasyStacks
Points:20
10 votes
Tags:
Basics of StacksData StructuresStacksReal world