Frequency-Greater Next Element

Time limit1sMemory limit512 MB

Summary
For each position, find the nearest value to its right whose total frequency in the array exceeds the frequency of the current element, or -1 if none exists.
Level

Medium5 of 10

Topics
Stack, Hash map, Array, Implementation
Solved
No attempts yet

Problem

There is a sequence A=A1,A2,⋯ ,ANA = A_1, A_2, \cdots, A_N of size NN. For each element AiA_i of the sequence, we want to find its frequency-greater next element NGF(i)NGF(i).

Let F(Ai)F(A_i) be the number of times AiA_i appears in AA. The frequency-greater next element of AiA_i is the leftmost number to its right whose number of appearances in AA is greater than F(Ai)F(A_i). If no such number exists, the frequency-greater next element is −1-1.

For example, if A=[1,1,2,3,4,2,1]A = [1, 1, 2, 3, 4, 2, 1], then F(1)=3F(1) = 3, F(2)=2F(2) = 2, F(3)=1F(3) = 1, and F(4)=1F(4) = 1. To the right of A1A_1 there is no number that appears more than 3 times, so NGF(1)=−1NGF(1) = -1. For A3A_3, A7A_7 lies to its right and F(A3=2)<F(A7=1)F(A_3 = 2) < F(A_7 = 1), so NGF(3)=1NGF(3) = 1. We have NGF(4)=2NGF(4) = 2, NGF(5)=2NGF(5) = 2, and NGF(6)=1NGF(6) = 1.

Input

The first line gives the size NN of the sequence AA (1≤N≤1,000,0001 \le N \le 1{,}000{,}000). The second line gives the elements A1,A2,⋯ ,ANA_1, A_2, \cdots, A_N of AA (1≤Ai≤1,000,0001 \le A_i \le 1{,}000{,}000).

Output

Print the NN numbers NGF(1),NGF(2),⋯ ,NGF(N)NGF(1), NGF(2), \cdots, NGF(N) separated by spaces.

Examples1

  1. Example 1

    Input
    7
    1 1 2 3 4 2 1
    
    Expected output
    -1 -1 1 2 2 1 -1