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 \leq n \leq 10^5$) — the total number of days.

The second line contains $n$ integers $u_1, u_2, \ldots, u_n$ ($1 \leq u_i \leq 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.

Difficulty: interview

Starter code:

Solutions:
counts = {}
rcount = {}

input()

m = 0
for i, x in enumerate(map(int, input().split())):
	if x in counts:
		rcount[counts[x]].remove(x)
		if not rcount[counts[x]]:
			del rcount[counts[x]]
		counts[x] += 1
		if counts[x] not in rcount: rcount[counts[x]] = set()
		rcount[counts[x]].add(x)
	else:
		counts[x] = 1
		if 1 not in rcount: rcount[1] = set()
		rcount[1].add(x)
	keys = list(rcount)
	if len(keys) == 2 and max(keys) - min(keys) == 1 and len(rcount[max(keys)]) == 1 or len(keys) == 2 and min(keys) == 1 and len(rcount[1]) == 1 or len(keys) == 1 and (len(rcount[keys[0]]) == 1 or keys[0] == 1):
		m = max(m, i)

print(m + 1)

from collections import defaultdict as dd
import math
def nn():
	return int(input())

def li():
	return list(input())

def mi():
	return list(map(int, input().split()))

def lm():
	return list(map(int, input().split()))






n=nn()

l=lm()

d={}

mnum=0
colors=0
singlecolors=0
maxstring=0
maxhit=0
for i, num in enumerate(l):
	if num in d:

		d[num]+=1

		if d[num]==mnum:
			maxhit+=1
		elif d[num]>mnum:
			mnum=max(mnum,d[num])
			maxhit=1
		if d[num]==2:
			singlecolors-=1
	else:
		d[num]=1
		singlecolors+=1
		if d[num]==mnum:
			maxhit+=1
		elif d[num]>mnum:
			mnum=max(mnum,d[num])
			maxhit=1
		colors+=1
	if (maxhit==1 and i==(mnum-1)*colors) or (maxhit>=colors-1 and singlecolors>=1):
		maxstring=i+1

print(maxstring)
		
	
	




n = int(input())
u = [int(u) for u in input().split()]

NMAX = 100005

suma = [0 for _ in range(NMAX)]
total = [0 for _ in range(NMAX)]

diferentes = 0
sol = 0
maximo = 1

for i, v in enumerate(u):
	if total[v] == 0:
		diferentes += 1
	else:
		suma[total[v]] -= 1
	total[v] += 1
	suma[total[v]] += 1

	maximo = max(maximo, total[v])

	#print(i, v, ":", diferentes)
	#print(suma)
	#print(total)
	#print(maximo, ":", suma[maximo], suma[maximo+1], diferentes-1)
	#print(maximo, ":", suma[maximo-1], suma[maximo], diferentes-1)

	if diferentes <= 1:
		sol = i

	if suma[maximo-1] == diferentes-1 and suma[maximo] == 1:
		sol = i

	if suma[maximo] == diferentes-1 and suma[1] == 1:
		sol = i

	if suma[1] == diferentes:
		sol = i
	
	#print("SOL", sol)

print(sol+1)


n = int(input())
u = list(map(int, input().split()))
cnts = [0 for _ in range(10 ** 5 + 1)]
cntcnt = [10**5+1] + [0 for _ in range(10 ** 5)]
b = 1
for i in range(n):
	cnts[u[i]] += 1
	cntcnt[cnts[u[i]] - 1] -= 1
	cntcnt[cnts[u[i]]] += 1

	nz = 10 ** 5 + 1 - cntcnt[0]
	j = i + 1
	if nz == 1:
		b = j
		continue
	if j % nz == 1:
		c = j // nz
		if cntcnt[c] + 1 == nz:
			b = j
			continue

	if cntcnt[1] and (j - 1) % (nz - 1) == 0 and cntcnt[(j - 1) // (nz - 1)] == nz - 1 + (j == nz):
		b = j
print(b)

def main():
    from sys import stdin, stdout

    def read():
        return stdin.readline().rstrip('\n')

    def read_array(sep=None, maxsplit=-1):
        return read().split(sep, maxsplit)

    def read_int():
        return int(read())

    def read_int_array(sep=None, maxsplit=-1):
        return [int(a) for a in read_array(sep, maxsplit)]

    def write(*args, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in args) + end)

    def write_array(array, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in array) + end)

    n = read_int()
    nums = read_int_array()
    counts = {}
    import collections
    inv_counts = collections.defaultdict(int)
    out = 0
    for i, x in enumerate(nums):
        c = inv_counts[x]
        if c:
            counts[c].remove(x)
            if not counts[c]:
                counts.pop(c)
        c += 1
        inv_counts[x] = c
        counts.setdefault(c, set()).add(x)
        if len(counts) == 2 and any(len(s) == 1 and ((k-1 in counts) or k == 1) for k, s in list(counts.items())):
            out = i + 1
        elif len(counts) == 1:
            k = next(iter(list(counts.keys())))
            if k == 1 or len(counts[k]) == 1:
                out = i + 1
    write(out)

main()


N = int(input())
A = [int(a) for a in input().split()]

C = [0] * 101010
ma = 0
macnt = 0
poscnt = 0
cntofone = 0
ans = 0
for i in range(N):
    C[A[i]] += 1
    if C[A[i]] > ma:
        ma = C[A[i]]
        macnt = 1
    elif ma == C[A[i]]:
        macnt += 1
    if C[A[i]] == 1:
        poscnt += 1
        cntofone += 1
    elif C[A[i]] == 2:
        cntofone -= 1
    if i <= 1 or (cntofone >= 1 and ((poscnt - 1) * ma == i)) or (macnt == 1 and (poscnt * (ma - 1) == i)):
        ans = i + 1

print(ans)


n = int(input())
a = [int(x) for x in input().split()]
arr = [0] * 100001
freqs = [0] * 100001
freqs[0] = n
minf, maxf = 0, 0
for ind, i in enumerate(a):
    arr[i] += 1
    freqs[arr[i]] += 1
    freqs[arr[i] - 1] -= 1
    if not freqs[arr[i] - 1] and minf == arr[i] - 1:
        minf += 1
    maxf = max(maxf, arr[i])
    if maxf == 1 or (freqs[maxf] + freqs[0] == n - 1 and freqs[1] == 1) or (freqs[maxf] == 1 and freqs[maxf - 1] + freqs[0] == n - 1):
        best = ind + 1
print(best)


from random import random
from collections import defaultdict
import math
import re
import fractions

N = int(input())
# N, M = map(int, input().split(" "))
A = list(map(int, input().split(" ")))
arr = [0]*(10**5+1)
existing = set()
for a in A:
  arr[a] += 1
  existing.add(a)

accumulate = defaultdict(int)
for count in arr:
  accumulate[count] += 1

for i in range(len(A)-1, -1, -1):
  a = A[i]
  length = i+1

  if len(existing) in [0, 1, length]:
    break

  expected_1 = (i+1-1)//(len(existing)-1)
  if accumulate[expected_1] * expected_1 + 1 == length and accumulate[1] == 1:
    break

  expected_k_1 = (i+1-1)//len(existing)
  if accumulate[expected_k_1] * expected_k_1 + expected_k_1 + 1 == length and accumulate[expected_k_1+1] == 1:
    break

  accumulate[arr[a]] -= 1
  arr[a] -= 1
  if arr[a] == 0:
    existing.discard(a)
  accumulate[arr[a]] += 1
  # print(accumulate)
print(length)



n = int(input())

a = list(map(int,input().split()))
if(n == 1 or n == 2):
    print(n)
    return
notpar = 0
occ = [0 for i in range(10**5 + 1)]
base = 1
gotone = False
leader = -1
leadby = 0
best = 0
occ[a[0]] += 1
cnt = 1
at1 = 1



for i in range(1, n):
    occ[a[i]] +=1
    
    if(occ[a[i]] == 1):
        notpar += 1
        at1 += 1
        cnt += 1
    elif(occ[a[i]] == 2):
        at1 -= 1
    if(occ[a[i]] == base):
        notpar -= 1
    elif(occ[a[i]] > base):
        if(gotone):
            if(a[i] != leader):
                base += 1
                notpar = cnt - 2
                leadby -= 1
                if(leadby == 0):
                    gotone = False
                    leader = -1
            else:
                leadby += 1
        else:
            gotone = True
            leader = a[i]
            leadby = 1
    if(notpar == 0 and (leadby == 1 or (leadby == 0 and base == 1)) or (notpar == 1 and leadby == 0 and at1 > 0)):
        best = i + 1
    if(cnt == 1):
        best = i + 1
    #print(i, base, leader, leadby, gotone, notpar, cnt)
print(best)
                    
                    


n = int(input())
ui = list(map(int,input().split()))
ar = [0] * 100001
ar2 = [0] * 100001
maxi = 1
mini = 1
ans = 1
for i in range(n):
    if ar[ui[i]] == 0:
        ar[ui[i]] = 1
        mini = 1
        ar2[1] += 1
    else:
        ar2[ar[ui[i]]] -= 1
        if ar2[ar[ui[i]]] == 0 and mini == ar[ui[i]]:
            mini += 1
        ar[ui[i]] += 1
        ar2[ar[ui[i]]] += 1
    maxi = max(maxi,ar[ui[i]])
    if (maxi == mini and mini == 1) or mini == i + 1:
        ans = i + 1
    elif maxi == mini + 1 and ar2[maxi] == 1:
        ans = i + 1
    elif mini == 1 and ar2[maxi] * maxi == i:
        ans = i + 1
    if ar2[maxi] * maxi == i+1:
        if i != n - 1:
            ans = i + 2
print(ans)


n = int(input())
A = list(map(int, input().split()))
B = [n] + [0] * (n + 1)
C = {}
calcset = set()
good = 0
next = 0
for i in range(n):
    C[A[i]] = C.get(A[i], 0) + 1
    B[C[A[i]] - 1] -= 1
    B[C[A[i]]] += 1
    if C[A[i]] > next:
        next = C[A[i]]
    calcset.add(A[i])
    if (B[next] + B[next - 1] == len(calcset) and B[next] == 1) or (B[1] == 1 and B[next] == len(calcset) - 1) or (next == 1 and B[next] == len(calcset)):
        good = max(good, i)
print(good + 1)


from collections import defaultdict as dd, deque
import sys

n = int(input())
A = [int(x) for x in input().split()]

C = dd(int)
CC = dd(int)

for a in A:
    C[a] += 1

for c in C:
    CC[C[c]] += 1

for a in reversed(A):
    if len(CC) == 2:
        aa,bb = sorted(list(CC.items()))
        k1,v1 = aa
        k2,v2 = bb
        if (k2-k1 == 1 and v2 == 1) or (k1 == 1 and v1 == 1):
            print(n)
            return
    elif len(CC) == 1:
        aa, = list(CC.items())
        k1,v1 = aa
        if k1 == 1 or v1 == 1:
            print(n)
            return

    CC[C[a]] -= 1
    if CC[C[a]] == 0:
        del CC[C[a]]
    C[a] -= 1
    if C[a] == 0:
        del C[a]
    if C[a]:
        CC[C[a]] += 1

    n -= 1


n = int(input())
u = [int(item) for item in input().split()]

d = {key: 0 for key in u}

for x in u:
    d[x] += 1

nb_occs = [0] * (n + 1)
for x in d:
    nb_occs[d[x]] += 1

s = set()
for i in range(len(nb_occs)):
    if nb_occs[i] != 0:
        s.add(i)

x = n - 1
count = len(s)
while 1:
    if len(s) == 1:
        items = list(s)
        if nb_occs[items[0]] == 1 or items[0] == 1:
            break
    if len(s) == 2:
        items = sorted(list(s))
        # print("here", s, nb_occs, items)
        if (items[0] == 1 and nb_occs[1] == 1) or (items[1] == items[0] + 1 and nb_occs[items[1]] == 1):
            break
    # print("x : ", x, s)
    # print(nb_occs)
    v = u[x]
    nb_occs[d[v]] -= 1
    if nb_occs[d[v]] == 0:
        s.remove(d[v])
    d[v] -= 1
    if d[v] != 0:
        nb_occs[d[v]] += 1
        s.add(d[v])
    x -= 1
print(x + 1)



from collections import Counter
import sys

n = int(input())
colors = list(map(int, sys.stdin.readline().split()))

total = 0
freqs = {colors[0] : 1}
freqs_of_freqs = {1:1}
max_length = 1

for index, color in enumerate( colors[1:] ):

    if color not in freqs:
        freqs[color] = 1
        freqs_of_freqs[1] = freqs_of_freqs.get(1, 0) + 1
    else:
        freqs_of_freqs[freqs[color]] -= 1
        if freqs_of_freqs[freqs[color]] == 0:
            del freqs_of_freqs[freqs[color]]
        freqs[color] += 1
        freqs_of_freqs[freqs[color]] = freqs_of_freqs.get(freqs[color], 0) + 1

    if len(freqs_of_freqs) == 2:
        l = list(freqs_of_freqs.keys())
        if max(l) == min(l) + 1 and freqs_of_freqs[max(l)] == 1:
            max_length = index + 2
        elif 1 in list(freqs_of_freqs.keys()) and freqs_of_freqs[1] == 1:
            max_length = index + 2
    elif len(freqs_of_freqs) == 1:
        if 1 in list(freqs_of_freqs.keys()) or 1 in list(freqs_of_freqs.values()):
            max_length = index + 2

print(max_length)



n=int(input().strip())
numbers=tuple(map(int,input().strip().split()))
occ=[0 for i in range(100001)]
places=[]
d={}
for k in range(0,len(numbers)):
    occ[numbers[k]]+=1
    if(occ[numbers[k]]-1 in list(d.keys())):
        if(d[occ[numbers[k]]-1]==1):
            d.pop(occ[numbers[k]]-1 )
        else:
            d[occ[numbers[k]]-1]-=1
    if(occ[numbers[k]] in list(d.keys())):
        d[occ[numbers[k]]]+=1
    else:
        d[occ[numbers[k]]]=1
    if(len(list(d.keys()))==2 and (1 in list(d.keys())) and (2 in list(d.keys()))):
        if(d[2]==1):
            places.append(k)
        if(d[1]==1):
            places.append(k)
    elif(len(list(d.keys()))==2 and (1 in list(d.keys()))):
        if(d[1]==1):
            places.append(k)
    elif(len(list(d.keys()))==2 ):
        lll=list(d.keys())
        if(lll[0]-lll[1]==1):
            if(d[lll[0]]==1):
                places.append(k)
        if (lll[1] - lll[0] == 1):
            if (d[lll[1]] == 1):
                places.append(k)
    elif(len(list(d.keys()))==1):
        jo=1
        for i in list(d.keys()):
            if(d[i]==1):
                places.append(k)
                jo=0
        if(jo):
            if(1 in list(d.keys())):
                places.append(k)
if(len(places)>0):
    print(places[-1]+1)
else:
    print(0)






n = int(input())
a = list(map(int,input().split()))

d = {}
for i in range(n):
	d[a[i]] = 0


# numOdd = 0
# for i in range(n):
# 	d[a[i]] += 1

# 	if(d[a[i]] % 2 != 0):
# 		numOdd += 1

# 	else:
# 		numOdd -= 1

# 	if(numOdd == 1):
# 		x = i+1

# print(x)

x = 1
for i in range(1,n):
	if(a[i] == a[i-1]):
		# print("yo")
		x = i+1
	else:
		break

ll = [0 for i in range(100001)]

l = []

for i in range(n):
	if(d[a[i]] != 0):
		if(ll[d[a[i]]] == 1):
			for c in range(len(l)):
				if l[c] == d[a[i]]:
					l.pop(c)
					break
		ll[d[a[i]]] -= 1

	d[a[i]] += 1
	if(d[a[i]] not in l):
		l.append(d[a[i]])
		l.sort()
	ll[d[a[i]]] += 1

	if(len(l) > 0 and l[0] == 0):
		l.pop(l[0])
	
	if(len(l) == 2):
		if(abs(l[0] - l[1]) == 1 and ll[l[1]] == 1):
			x = max(x,i+1)
		elif(l[0] == 1 and ll[1] == 1):
			x = max(x,i+1)
	if(len(l) == 1 and l[0] == 1):
		x = max(x,i+1)

print(x)

n = int(input())
arr = [int(x) for x in input().split()]

counts = [0] * 100000
count_to_color = {}

mx = 0
for i in range(n):
    color = arr[i] - 1
    # print(i, color, count_to_color)

    if counts[color] > 0:
        count_to_color[counts[color]].remove(color)
        if not count_to_color[counts[color]]:
            del count_to_color[counts[color]]
    counts[color] += 1
    count = counts[color]

    if count not in count_to_color:
        count_to_color[count] = set()
    count_to_color[count].add(color)

    if len(count_to_color) == 1:
        if 1 in count_to_color:
            mx = max(mx, i)
        if len(list(count_to_color.values())[0]) == 1:
            mx = max(mx, i)
    if len(count_to_color) == 2:
        count_keys = sorted(list(count_to_color.keys()))
        if count_keys[0] == 1 and len(count_to_color[count_keys[0]]) == 1:
            mx = max(mx, i)
        if count_keys[0] + 1 == count_keys[1] and len(count_to_color[count_keys[1]]) == 1:
            mx = max(mx, i)

print(mx + 1)


n = int(input())
apr, l, f, ans = 0, [0] * 100001, [0] * 100001, 1
i = 0
for x in input().split():
    x = int(x)
    if l[x] == 0:
        l[x] += 1
        apr += 1
        f[1] += 1
    else:
        f[l[x]] -= 1
        l[x] += 1
        f[l[x]] += 1

    if i % apr == 0:
        tmp = i // apr
        if f[tmp] == apr - 1:
            ans = max(ans, i + 1)

    if apr > 1 and i % (apr - 1) == 0:
        tmp = i // (apr - 1)
        if f[tmp] == apr - 1 or f[tmp] == apr:
            ans = max(ans, i + 1)
    i += 1
print(ans)


n = int(input())
a = list(map(int, input().split()))
ans = n

s = set()
x = {i: 0 for i in range(1, 100001)}
y = {}
for i in range(n):
    e = a[i]
    c = x[e]
    if c:
        y[c].remove(e)
        if len(y[c]) == 0:
            s.remove(c)
    x[e] += 1
    c += 1
    if c not in y:
        y[c] = set({e})
    else:
        y[c].add(e)
    s.add(c)
    if len(s) == 2:
        l = list(s)
        p = l[0]
        q = l[1]
        py = len(y[p])
        qy = len(y[q])
        if py == 1:
            if p == q + 1 or p == 1:
                ans = i + 1
        if qy == 1:
            if q == p + 1 or q == 1:
                ans = i + 1

print(ans)


from collections import defaultdict

def isValid(n, m, freq, found):
    f = (n - 1)//m
    if f != (n - 1)/m:
        return 0
    flag = 0
    for i in found:
        if freq[i] != 0:
            if flag == 0 and freq[i] == f or freq[i] == f + 1:
                if freq[i] == f + 1:
                    flag = 1
            elif flag == 1 and freq[i] == f:
                continue
            else:
                return 0
    if flag == 0:
        return 0
    return 1

def isValid2(n, m, freq, found):
    f = (n - 1)//(m - 1)
    if f != (n - 1)/(m - 1):
        return 0
    flag = 0
    for i in found:
        if freq[i] != 0:
            if flag == 0 and freq[i] == f or freq[i] == 1:
                if freq[i] == 1:
                    flag = 1
            elif flag == 1 and freq[i] == f:
                continue
            else:
                return 0
    if flag == 0:
        return 0
    return 1

n = int(input())
freq = {}
freq = defaultdict(lambda: 0, freq)
a = list(map(int, input().split()))
m = len(set(a))
found = []
#calculation of freq
for i in a:
    freq[i] += 1
    found.append(i)
# print(freq)
found = list(set(found))
# print(found)
for i in range(n - 1, -1, -1):
    if isValid(i + 1, m, freq, found) == 0 and isValid2(i + 1, m, freq, found) == 0:
        freq[a[i]] -= 1
        if freq[a[i]] == 0:
            m -= 1
    else:
        # print(isValid(i + 1, m, freq))
        # print(isValid2(i + 1, m, freq))
        print(i + 1)
        break

#Bhargey Mehta (Sophomore)
#DA-IICT, Gandhinagar
import sys, math, queue
#sys.stdin = open("input.txt", "r")
MOD = 10**9+7

n = int(input())
u = list(map(int, input().split()))
f = {}
ff = {}
ans = 1
for i in range(n):
    if len(ff) == 1:
        ans = i+1
    if u[i] in f: f[u[i]] += 1
    else: f[u[i]] = 1
    
    if f[u[i]]-1 in ff:
        if ff[f[u[i]]-1] == 1: del ff[f[u[i]]-1]
        else: ff[f[u[i]]-1] -= 1

    if f[u[i]] in ff: ff[f[u[i]]] += 1
    else: ff[f[u[i]]] = 1

    if len(ff) == 2:
        k1, k2 = sorted(ff.keys())
        if k2-k1 == 1:
            if ff[k2] == 1:
                ans = i+1
        if k1 == 1:
            if ff[k1] == 1:
                ans = i+1
print(ans)

import sys
input = sys.stdin.readline

n=int(input())
A=list(map(int,input().split()))

from collections import Counter
C=Counter(A)

D=Counter(list(C.values()))
MAX=max(C.values())
MIN=min(C.values())

#print(C)
#print(D)

for i in range(n-1,-1,-1):
    if MAX==MIN+1 and D[MAX]==1:
        print(i+1)
        return

    if len(D)==2 and D[1]==1:
        print(i+1)
        return

    if len(D)==1 and D[1]>0:
        print(i+1)
        return

    if len(D)==1 and list(D.values())==[1]:
        print(i+1)
        return
        

    a=A[i]
    
    if MAX==C[a] and D[MAX]==1:
        MAX-=1
    if MIN==C[a]:
        MIN-=1
        
    D[C[a]]-=1
    if D[C[a]]==0:
        del D[C[a]]

    if MIN==0:
        MIN=min(D.keys())


    C[a]-=1

    if C[a]==0:
        del C[a]

    else:
        D[C[a]]+=1

    #print(C)
    #print(D)
    #print(MAX,MIN)


N = int(input())
arr = [int(x) for x in input().split()]
cnt = dict()
brr = set()
crr = [0 for _ in range(100001)]
for i in range(1, N + 1):
    cnt[i] = set()
answer = 1
for i in range(N):
    u = arr[i]
    crr[u] += 1
    if crr[u] > 1:
        cnt[crr[u] - 1].remove(u)
        if len(cnt[crr[u] - 1]) == 0:
            brr.remove(crr[u] - 1)
    cnt[crr[u]].add(u)
    brr.add(crr[u])
    if len(brr) == 1:
        drr = list(brr)
        if drr[0] == 1 or len(cnt[drr[0]]) == 1:
            answer = i + 1
    elif len(brr) == 2:
        drr = list(brr)
        drr.sort()
        if drr[0] == 1 and len(cnt[1]) == 1:
            answer = i + 1
        elif drr[1] == drr[0] + 1 and len(cnt[drr[1]]) == 1:
            answer = i + 1
print(answer)


n = int(input())
colors = list(map(int, input().split()))
cnt = [0 for _ in range(100001)]
vals = dict()
ind = 1
for i in range(n):
    el = colors[i]
    if cnt[el] != 0:
        vals[cnt[el]] -= 1
        if vals[cnt[el]] == 0:
            del vals[cnt[el]]
    cnt[el] += 1
    if cnt[el] in vals:
        vals[cnt[el]] += 1
    else:
        vals[cnt[el]] = 1
    if len(vals) == 2:
        tmp = list(vals.keys())
        tmp.sort()
        if tmp[0] == 1 and vals[tmp[0]] == 1 or tmp[1] - tmp[0] == 1 and vals[tmp[1]] == 1:
            ind = i
    elif len(vals) == 1 and list(vals.keys())[0] == 1:
        ind = i
if (cnt[colors[0]] == n):
    print(n)
else:
    print(ind + 1)