This problem is same as the previous one, but has larger constraints.

Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.

For each of the n days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the i-th day has a ribbon with color u_i. Shiro wants to know the largest number x, such that if we consider the streak of the first x days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining x - 1 will have the same number of occurrences.

For example, consider the following sequence of u_i: [2, 2, 1, 1, 5, 4, 4, 5]. Then x = 7 makes a streak, since if we remove the leftmost u_i = 5, each ribbon color will appear exactly twice in the prefix of x - 1 days. Note that x = 8 doesn't form a streak, since you must remove exactly one day. 

Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.

Input

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the total number of days.

The second line contains n integers u_1, u_2, …, u_n (1 ≤ u_i ≤ 10^5) — the colors of the ribbons the cats wear. 

Output

Print a single integer x — the largest possible streak of days.

Examples

Input


13
1 1 1 2 2 2 3 3 3 4 4 4 5


Output


13

Input


5
10 100 20 200 1


Output


5

Input


1
100000


Output


1

Input


7
3 2 1 1 4 5 1


Output


6

Input


6
1 1 1 2 2 2


Output


5

Note

In the first example, we can choose the longest streak of 13 days, since upon removing the last day out of the streak, all of the remaining colors 1, 2, 3, and 4 will have the same number of occurrences of 3. Note that the streak can also be 10 days (by removing the 10-th day from this streak) but we are interested in the longest streak.

In the fourth example, if we take the streak of the first 6 days, we can remove the third day from this streak then all of the remaining colors 1, 2, 3, 4 and 5 will occur exactly once.
"""
Author    : raj1307 - Raj Singh
Institute : Jalpaiguri Government Engineering College
Date      : 11.05.19
"""
from __future__ import division, print_function
import itertools,os,sys

from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    from builtins import str as __str__
    str = lambda x=b'': x if type(x) is bytes else __str__(x).encode()

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        self._writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self._buffer.write if self._writable else None

    def read(self):
        return self._buffer.read() if self._buffer.tell() else os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b, ptr = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)), self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
            self.newlines += b.count(b'\n') + (not b)
        self.newlines -= 1
        return self._buffer.readline()

    def flush(self):
        if self._writable:
            os.write(self._fd, self._buffer.getvalue())
            self._buffer.truncate(0), self._buffer.seek(0)


sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b'\r\n')


def print(*args, **kwargs):
    sep, file = kwargs.pop('sep', b' '), kwargs.pop('file', sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop('end', b'\n'))
    if kwargs.pop('flush', False):
        file.flush()



def ii(): return int(input())
def si(): return str(input())
def mi(): return map(int,input().strip().split(" "))
def li(): return list(mi())

#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify, #heappop ,heappush, heapreplace
#from math import ceil,floor,log,sqrt,factorial,pow,pi
#from bisect import bisect_left,bisect_right
#from decimal import *,threading

def dmain():
    sys.setrecursionlimit(100000000)
    threading.stack_size(20480000)
    thread = threading.Thread(target=main)
    thread.start()

abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[0] 
def sort2(l):return sorted(l, key=getKey)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]
def powerMod(x,y,p):
    res = 1
    x %= p
    while y > 0:
        if y&1:
            res = (res*x)%p
        y = y>>1
        x = (x*x)%p1
    return res
def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

# For getting input from input.txt file 
#sys.stdin = open('input.txt', 'r')  
  
# Printing the Output to output.txt file 
#sys.stdout = open('output.txt', 'w') 

def main():
   
    n=ii()
    l=li()
    
    f=[0]*1000000
    cnt=[0]*1000000
    ans=1
    mx=0   
    for i in range(n):
        
        cnt[f[l[i]]]-=1
        f[l[i]]+=1
        cnt[f[l[i]]]+=1
        
        mx=max(mx,f[l[i]])
        
        
        if cnt[1]==i+1 or cnt[i+1]==1:
            ans=i+1
        
        elif cnt[1]==1 and  cnt[mx]*mx==i:
            ans=i+1
        
        elif cnt[mx]==1 and cnt[mx-1]*(mx-1)==i+1-mx:
            ans=i+1
        
    print(ans)        
        
        
        
        
        
        
        
        
        
        
    
    
    
    
    
    
    
    
    
    """
    f=[0]*11
    for i in range(n):
        f[l[i]]+=1
    #print(f)
    if len(list(set(l)))==n:
        print(n)
        exit()
    
    for i in range(n-1,-1,-1):
        if len(list(set(f)))==3:
            
            c=list(set(f))
            a,b=0,0
            num=c[-1]
            #print(c)
            flag=0
            for j in range(len(f)):
                if f[j]!=0:    
                    if f[j]==num:
                        #print(f[j],num)
                        a+=1
                    else:
                        #print(f[j],num)
                        b+=1
                    if a==2:
                        minus=c[-2]
                        
                        mm=c[-1]
                        flag=1
                        #print(c)
                        break
                    elif b==2:
                        minus=c[-1]
                        mm=c[-2]
                        flag=1
                        #print(c)
                        break
            
            #print(a,b)
            #print(minus,mm,'k')
            if flag==0:
                minus=max(c[-1],c[-2])
                mm=min(c[-1],c[-2])
            #print(f)
            for k in range(11):
                if f[k]==minus:
                    no=k
                    break
            #print(minus,mm)  
            cnt=0
            for p in range(len(f)):
                if f[p]==minus:
                    cnt+=1
            if minus-1==mm or f[no]-1==0 and cnt==1:
                #print(c)
                #print('k')
                print(i+1)
                exit()
            else:
                f[l[i]]-=1
        elif len(list(set(f)))==2 and i!=n-1:
            #print('i')
            print(i+1)
            exit()
            
        
        else:
            #print('i')
            f[l[i]]-=1
            #print(f)
            """
            
 
    
    
    
    
    
    
    
    
    
       
   
   
   
   
   
   
   
  

if __name__ == "__main__":
    main()
    #dmain()
    