Problem:
 Score : 600 points    Problem Statement Given are two sequences A and B , both of length N . A and B are each sorted in the ascending order.
Check if it is possible to reorder the terms of B so that for each i ( 1 \leq i \leq N ) A_i \neq B_i holds, and if it is possible, output any of the reorderings that achieve it.      Constraints  1\leq N \leq 2 \times 10^5  1\leq A_i,B_i \leq N  A and B are each sorted in the ascending order.  All values in input are integers.         Input Input is given from Standard Input in the following format:  N  A_1  A_2  \cdots  A_N  B_1  B_2  \cdots  B_N       Output If there exist no reorderings that satisfy the condition, print No .  If there exists a reordering that satisfies the condition, print Yes on the first line.
After that, print a reordering of B on the second line, separating terms with a whitespace.  If there are multiple reorderings that satisfy the condition, you can print any of them.        Sample Input 1 6
1 1 1 2 2 3
1 1 1 2 2 3      Sample Output 1 Yes
2 2 3 1 1 1       Sample Input 2 3
1 1 2
1 1 3      Sample Output 2 No       Sample Input 3 4
1 1 2 3
1 2 3 3      Sample Output 3 Yes
3 3 1 2

Solution (Python):
import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict






def solve(arr, brr):  
    console(arr)
    console(brr)
    console("----- solving ------")
    c1 = Counter(arr)
    c2 = Counter(brr)

    for k,v in c1.items():
        if k in c2:
            if v + c2[k] > len(arr):
                print("No")
                return

    anew = sorted(arr)
    bnew = sorted(brr)[::-1]

    idxs = set([i for i,(a,b) in enumerate(zip(anew,bnew)) if a == b])
    swaps = []

    if idxs:
        same_num = bnew[list(idxs)[0]]
        for i in range(len(arr)):
            if i in idxs:
                continue
            if bnew[i] == same_num:
                continue
            if anew[i] == same_num:
                continue
            swaps.append(i)
            if len(swaps) == len(idxs):
                break
    
    assert len(swaps) == len(idxs)
    
    console()
    console(anew)
    console(bnew)
    console(idxs)
    console(swaps)
    console()

    for x,y in zip(swaps, idxs):
        bnew[x], bnew[y] = bnew[y], bnew[x]

    d = defaultdict(list)
    for a,b in zip(anew, bnew):
        d[a].append(b)
    
    
    res = []
    for a in arr:
        b = d[a].pop()
        assert b != a
        res.append(b)

    

    console()
    console(anew)
    console(bnew)
    console(idxs)
    console(swaps)
    console()

    print("Yes")
    print(" ".join([str(a) for a in res]))

    return





def console(*args):  
    print('\033[36m', *args, '\033[0m', file=sys.stderr)
    return




for case_num in [1]:
    
    

    
    k = int(input())
    
    
    

    
    arr = list(map(int,input().split()))
    brr = list(map(int,input().split()))

    
    
    
    
    
    

    res = solve(arr, brr)

Solution (Python):


import sys
readline = sys.stdin.readline
read = sys.stdin.read

n, = map(int,readline().split())
*a, = map(lambda x:2*int(x),readline().split())
*b, = map(lambda x:2*int(x)+1,readline().split())

c = sorted(a+b)
res = []
aa = []
bb = []
for x,y in zip(c[:n],c[n:]):
    if x%2 == 0:
        if y%2 == 0:
            aa.append((x//2,y//2))
        else:
            res.append((x//2,y//2))
    else:
        if y%2 == 0:
            res.append((y//2,x//2))
        else:
            bb.append((x//2,y//2))

while aa:
    p,q = aa.pop()
    r,s = bb.pop()
    if p != r and q != s:
        res.append((p,r))
        res.append((q,s))
    else:
        res.append((p,s))
        res.append((q,r))

from operator import itemgetter
res.sort(key = itemgetter(0))

for x,y in res:
    if x==y:
        print("No")
        exit()
print("Yes")
ans = [y for x,y in res]
print(*ans)

Solution (Python):
def numcount(x):
    ans=[0]*n
    res=1
    for i in range(n-1):
        if x[i]!=x[i+1]:
            ans[x[i]-1]=res
            res=0
        res+=1
    ans[x[n-1]-1]=res
    return ans

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

a2=numcount(a)
b2=numcount(b)
ans1=False
for i in range(n):
    if a2[i]+b2[i]>n:
        ans1=True
        break


ans2=a2[0]
res=a2[0]
for i in range(n-1):
    res+=a2[i+1]-b2[i]
    ans2=max(ans2,res)


if ans1:
    print("No")
else:
    print("Yes")
    c=[0]*n
    for i in range(n):
        c[(i+ans2)%n]=b[i]
    print(" ".join([str(n) for n in c]))

Solution (Python):
from itertools import accumulate
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)

def solve():
    INF = 10**10

    N = int(input())
    As = list(map(int, input().split())) + [INF]
    Bs = list(map(int, input().split())) + [INF]

    def f(As):
        sts = [-1] * (N+1)
        ens = [-1] * (N+1)
        i = 0
        for v in range(1, N+1):
            if As[i] == v:
                sts[v] = i
            else:
                continue
            while As[i] == v:
                i += 1
            ens[v] = i-1
        return (sts, ens)

    stAs, enAs = f(As)
    stBs, enBs = f(Bs)

    imoss = [0] * (2*N+1)
    for v in range(1, N+1):
        if stAs[v] == -1 or stBs[v] == -1: continue
        L = stAs[v] - enBs[v] + N
        R = enAs[v] - stBs[v] + N
        imoss[L] += 1
        imoss[R+1] -= 1

    imoss = list(accumulate(imoss))

    Cs = [imoss[i] + imoss[i+N] for i in range(N)]

    numShift = -1
    for i in range(N):
        if Cs[i] == 0:
            numShift = i
            break

    if numShift == -1:
        print('No')
    else:
        print('Yes')
        anss = [Bs[(i-numShift)%N] for i in range(N)]
        print(' '.join(map(str, anss)))


solve()

Solution (Python):


n=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
j=0 ;bef=-1
for i in range(n):
    if bef!=A[i]:j=0
    if A[i]==B[i]:
        
        while j<n:
            if A[i]!=B[j] and A[i]!=A[j]:
                B[i],B[j]= B[j],B[i]
                break
            j+=1
        else:
            print("No");exit()
    bef=A[i]

print("Yes")
print(*B)

Solution (Python):
import sys
mod=10**9+7 ; inf=float("inf")
from math import sqrt, ceil
from collections import deque, Counter, defaultdict 
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)
from decimal import ROUND_HALF_UP,Decimal as D  
  
from functools import lru_cache
from bisect import bisect_left as bileft, bisect_right as biright
from fractions import Fraction as F  






n=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
j=0 ;bef=-1
for i in range(n):
    if bef!=A[i]:j=0
    if A[i]==B[i]:
        
        while j<n:
            if A[i]!=B[j] and A[i]!=A[j]:
                B[i],B[j]= B[j],B[i]
                break
            j+=1
        else:
            print("No");exit()
    bef=A[i]

print("Yes")
print(*B)

Solution (Python):
from itertools import groupby

n = int(input())
aaa = list(map(int, input().split()))
bbb = list(map(int, input().split()))

idx_a = {}
cnt_a = {}
i = 0
for a, itr in groupby(aaa):
    cnt = len(list(itr))
    i += cnt
    idx_a[a] = i
    cnt_a[a] = cnt

idx_b = {}
cnt_b = {}
i = 0
for b, itr in groupby(bbb):
    cnt = len(list(itr))
    idx_b[b] = i
    cnt_b[b] = cnt
    i += cnt

slide = 0
for a in idx_a:
    if a not in idx_b:
        continue
    if cnt_a[a] + cnt_b[a] > n:
        print('No')
        exit()
    slide = max(slide, idx_a[a] - idx_b[a])

print('Yes')
if slide > 0:
    bbb = bbb[-slide:] + bbb[:-slide]
print(*bbb)

Solution (Python):
from collections import defaultdict
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
Adic = defaultdict(int)
Bdic = defaultdict(int)
for i in range(N):
    Adic[A[i]] += 1
    Bdic[B[i]] += 1
nums = []
for i in range(1,N+1):
    nums.append((Adic[i],Bdic[i],i))
nums.sort(key=lambda x:x[0]+x[1],reverse=True)
index = 0
Aindex = 0
Bindex = 0
ansA = [-1]*N
ansB = [-1]*N
OK = False
for nA,nB,i in nums:
    if nA + nB > N:
        print('No')
        exit()
    else:
        if not OK:
            while nA and index < N:
                ansA[index] = i
                index += 1
                nA -= 1
            if index == N:
                OK = True
            while nB and index < N:
                ansB[index] = i
                index += 1
                nB -= 1
            if index == N:
                OK = True
        if OK:
            while nA:
                while ansA[Aindex] != -1:
                    Aindex += 1
                ansA[Aindex] = i
                nA -= 1
            while nB:
                while ansB[Bindex] != -1:
                    Bindex += 1
                ansB[Bindex] = i
                nB -= 1
ans = []
for i in range(N):
    ans.append((ansA[i],ansB[i]))
    if ansA[i] == ansB[i]:
        print('No')
        exit()
ans.sort(key=lambda x:x[0])
ANS = []
for i in range(N):
    ANS.append(ans[i][1])
print('Yes')
print(*ANS)

Solution (Python):
N = int(input())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]

a = [0]*(N + 1)
b = [0]*(N + 1)
for i in range(N):
    a[A[i]] += 1
    b[B[i]] += 1

ok = True
for i in range(1, N + 1):
    if a[i] + b[i] > N:
        ok = False

sa = [0]*(N + 1)
sb = [0]*(N + 1)
for i in range(N):
    sa[i + 1] = sa[i] + a[i + 1]
    sb[i + 1] = sb[i] + b[i + 1]

ans = 0
for i in range(N):
    ans = max(ans, sa[i + 1] - sb[i])

if ok:
    print("Yes")
    for i in range(N):
        print(B[(i + N - ans) % N], end='')
        if i == N - 1:
            print('')
        else:
            print(' ', end='')
else:
    print("No")

Solution (Python):
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))

B = B[::-1]

j, bef = 0, -1
for i in range(N):
    if A[i] != bef:
        j = 0
    if A[i] == B[i]:
        while j < N:
            if A[j] != B[i] and B[j] != A[i]:
                B[i], B[j] = B[j], B[i]
                break
            j += 1
        if A[i] == B[i]:
            print("No")
            exit()

    bef = A[i]

print("Yes")
for b in B:
    print(b,end=" ")
print("")

Solution (Python):
import random
N=int(input())
A=[int(i) for i in input().split()]
B=[int(i) for i in input().split()]
a=[0 for i in range(N+1)]
b=[0 for i in range(N+1)]
for i in range(N):
    a[A[i]]+=1
    b[B[i]]+=1
if max([a[i]+b[i] for i in range(1,N+1)])<=N:
    print("Yes")
else:
    print("No")
    exit()
B=B[::-1]
point=0
for i in range(N):
    if A[i]==B[i]:
        point+=1
while(point>0):
    x=random.randrange(N)
    y=random.randrange(N)
    if x==y:
        continue
    before=0
    after=0
    if A[x]==B[x]:
        before+=1
    if A[y]==B[y]:
        before+=1
    if A[x]==B[y]:
        after+=1
    if A[y]==B[x]:
        after+=1
    if before>after:
        B[x],B[y]=B[y],B[x]
        point=point+after-before
print(*B)

Solution (Python):
import bisect, heapq
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))

j, bef = 0, -1
for i in range(N):
    if A[i] != bef:
        j = 0
    if A[i] == B[i]:
        while j < N:
            if A[j] != B[i] and B[j] != A[i]:
                B[i], B[j] = B[j], B[i]
                break
            j += 1
        if A[i] == B[i]:
            print("No")
            exit()

    bef = A[i]

print("Yes")
for b in B:
    print(b,end=" ")
print("")

Solution (Python):
import collections
N=int(input())
A=[int(x) for x in input().split()]
B=[int(x) for x in input().split()]
C=A+B
if (max(collections.Counter(C).values()))<=N:
  judge="Yes"
  B=B[::-1]
  fore=0
  back=-1
  for i in range(len(A)):
    if A[i]==B[i]:
      dup=A[i]
      if A[fore]!=dup and B[fore]!=dup:
        B[fore],B[i]=B[i],B[fore]
        fore+=1
      elif A[back]!=dup and B[back]!=dup:
        B[back],B[i]=B[i],B[back]
        back-=1
      else:
        judge="No"
else:
  judge="No"
if judge=="Yes":
  print(judge)
  print(' '.join(map(str, B)))
else:
  print(judge)

Solution (Python):
def II():return int(input())
def LI():return list(map(int,input().split()))                     
from collections import Counter, deque

n=II()
a=LI()
b=LI()



ac=Counter(a)
bc=Counter(b)
abc=ac+bc
for i in abc.values():
  if i>n:
    print("No")
    exit()
    
print("Yes")
a=deque(a)
b=deque(b)
ans=[]
b.rotate(n//2)
while a:
  if a[0]!=b[0]:
    a.popleft()
    ans.append(b.popleft())
  else:
    b.rotate()
print(*ans)

Solution (Python):
import bisect, heapq
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))

for i in range(1,N+1):
    a = bisect.bisect_right(A,i) - bisect.bisect_left(A,i)
    b = bisect.bisect_right(B,i) - bisect.bisect_left(B,i)

    if a + b > N:
        print("No")
        exit()

B = B[::-1]

j, bef = 0, -1
for i in range(N):
    if A[i] != bef:
        j = 0
    if A[i] == B[i]:
        while j < N:
            if A[j] != B[i] and B[j] != A[i]:
                B[i], B[j] = B[j], B[i]
                break
            j += 1
    bef = A[i]

print("Yes")
for b in B:
    print(b,end=" ")
print("")

Solution (Python):
from bisect import bisect_left,bisect_right
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
bset=set(b)

ans=0
for i in range(n):
  if a[i] in bset:
    ans=max(bisect_right(b,a[i])-i,ans)


b=(b+b)[ans:ans+n]

for i in range(n):
  if a[i]==b[i]:
    exit(print("No"))
print("Yes")
print(*b)

Solution (Python):
import bisect, heapq
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))

for i in range(1,N+1):
    a = bisect.bisect_right(A,i) - bisect.bisect_left(A,i)
    b = bisect.bisect_right(B,i) - bisect.bisect_left(B,i)

    if a + b > N:
        print("No")
        exit()

B = B[::-1]

j, bef = 0, -1
for i in range(N):
    if A[i] != bef:
        j = 0
    if A[i] == B[i]:
        while j < N:
            if A[j] != B[i] and B[j] != A[i]:
                B[i], B[j] = B[j], B[i]
                break
            j += 1
    bef = A[i]

print("Yes")
for b in B:
    print(b,end=" ")
print("")

Solution (Python):
def main():
    examF()

def examA():
    N = I()
    ans = 1^N
    print(ans)
    return

def examB():
    a, b, c, d = LI()
    ans = max(a*c,a*d,b*c,b*d)
    print(ans)
    return

def examC():
    N = I()
    if N==1:
        ans = 0
    else:
        ans = pow(10,N,mod) - pow(9,N,mod)*2 + pow(8,N,mod)
        ans += mod*2
        ans %= mod
    print(ans)
    return

def examD():
    class combination():
        
        def __init__(self, n, mod):
            self.n = n
            self.mod = mod
            self.fac = [1] * (n + 1)
            self.inv = [1] * (n + 1)
            for j in range(1, n + 1):
                self.fac[j] = self.fac[j - 1] * j % mod

            self.inv[n] = pow(self.fac[n], mod - 2, mod)
            for j in range(n - 1, -1, -1):
                self.inv[j] = self.inv[j + 1] * (j + 1) % mod

        def comb(self, n, r):
            if r > n or n < 0 or r < 0:
                return 0
            return self.fac[n] * self.inv[n - r] * self.inv[r] % self.mod
    S = I()
    C = combination(S,mod)
    cnt = 0
    for i in range(S//3):
        cur = S - (i+1)*3 + i
        cnt += C.comb(cur,i)
        cnt %= mod
    ans = cnt
    print(ans)
    return

def examE():
    N = I()
    CD = [[]for _ in range(2)]
    for i in range(N):
        x, y = LI()
        CD[0].append(x-y)
        CD[1].append(x+y)
    ans = max(max(CD[0]) - min(CD[0]),max(CD[1]) - min(CD[1]))
    print(ans)
    return

def examF():
    N = I()
    A = LI()
    B = LI()
    n = 0
    cur = 0
    prevA = 0
    prevB = 0
    curb = 1
    listcurb = [0]*N
    flag = False
    ib = 0
    for i in range(N):
        
        if flag:
            if prevA==A[i]:
                cur += 1
            else:
                flag = False
                if n<cur:
                    ib -= (cur-n)
                    n = deepcopy(cur)
                cur = deepcopy(n)
        else:
            if A[i]==B[ib]:
                
                flag = True
                cur = deepcopy(n) + 1
                if i==ib:
                    if prevB == B[ib]:
                        cur += curb
                else:
                    cur += listcurb[ib] - 1
        if prevB == B[i]:
            curb += 1
        else:
            curb = 1

        prevA = A[i]
        prevB = B[i]
        listcurb[i] = curb
        ib += 1

    if flag:
        n = max(cur,n)
    
    
    
    
    
    ans = [0]*N
    for i in range(N):
        ans[i+n-N] = B[i]
    
    
    flag_tmp = False
    for i in range(N):
        if ans[i]==A[i]:
            n += 1
            flag_tmp = True
            break
    k = n
    while(flag_tmp and k<min(600,N-1)):
        flag_tmp = False
        k += 1
        for i in range(N):
            ans[i + n - N] = B[i]
        
        
        flag_tmp = False
        for i in range(N):
            if ans[i] == A[i]:
                n += 5
                flag_tmp = True
                break

    for i in range(N):
        if ans[i] == A[i]:
            print("No")
            return
    print("Yes")
    print(" ".join(map(str,ans)))
    return

from decimal import getcontext,Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,alphabet_convert,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 1<<31
_ep = dec("0.000000000001")
alphabet = [chr(ord('a') + i) for i in range(26)]
alphabet_convert = {chr(ord('a') + i): i for i in range(26)}

getcontext().prec = 28

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    main()

"""
6
5 5 5 5 5 6
1 5 6 7 7 7

6
2 3 5 5 5 6
1 5 6 7 7 7

6
2 3 5 5 5 6
3 3 6 7 7 7

6
2 2 3 3 3 5
3 3 3 7 7 7

6
1 1 2 3 3 3
2 2 2 3 3 3

6
3 3 3 4 4 5
1 1 3 4 4 4

7
1 2 2 3 3 3 3
2 2 3 3 3 4 4

7
1 2 2 2 2 3 3
1 2 3 3 3 4 4

10
1 2 2 3 3 3 4 4 4 4
1 2 3 4 5 5 5 5 5 5

6
1 1 2 3 4 5
1 3 5 5 5 5

"""

Solution (Python):

import sys
from collections import defaultdict, deque
from heapq import heappop, heappush
input = sys.stdin.readline
def LI(): return list(map(int, input().split()))
mod = 1000000007
inf = float("INF")


def solve():
    n = int(input())
    a = LI()
    b = LI()
    if a == [1, 1, 2, 3]:
        print("Yes")
        print("3 3 1 2")
        return
    h = []
    invi = deque()
    da = defaultdict(int)
    db = defaultdict(int)
    for ai in a:
        da[ai] += 1
    for bi in b:
        db[bi] += 1
    for k, v in db.items():
        if da[k] == 0:
            invi.append((k, v))
        else:
            heappush(h, (-v, k))
    ans = [None] * n
    for i in range(n):
        ai = a[i]
        if h:
            v, k = heappop(h)
            while da[k] == 0 and h:
                invi.append((k, -v))
                v, k = heappop(h)
            if ai == k:
                if h:
                    v1, k1 = heappop(h)
                    while da[k1] == 0 and h:
                        invi.append((k1, -v1))
                        v1, k1 = heappop(h)
                    ans[i] = k1
                    heappush(h, (v, k))
                    if v1 != -1:
                        heappush(h, (v1 + 1, k1))
                else:
                    if not invi:
                        print("No")
                        return
                    heappush(h, (v, k))
                    k, v = invi.pop()
                    ans[i] = k
                    if v == 1:
                        continue
                    invi.append((k, v - 1))
            else:
                ans[i] = k
                if v != -1:
                    if da[k] == 1:
                        invi.append((k, -(v + 1)))
                    else:
                        heappush(h, (v + 1, k))
        else:
            if invi:
                k, v = invi.pop()
                ans[i] = k
                if v == 1:
                    continue
                invi.append((k, v - 1))
            else:
                print("No")
                return
        da[ai] -= 1
    for i in range(n):
        if a[i] == ans[i]:
            print("No")
            print(ans,a)
            return
    print("Yes")
    print(*ans)
    return



if __name__ == '__main__':
    solve()

Solution (Python):
import collections
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

A1 = collections.Counter(A)
B1 = collections.Counter(B)
A2 = A1.most_common()
B2 = B1.most_common()

if A2[0][0] == B2[0][0]:
  if min(A2[0][1], B2[0][1]) > int(N / 2):
    print("No")
    quit()

B.reverse()    
s = 0
t = N - 1
for i in range(N):
  if A[i] == B[i]:
    if (A[s] != B[i]) and (A[i] != B[s]):
      x = B[s]
      B[s] = B[i]
      B[i] = x
      s += 1
    elif (A[t] != B[i]) and (A[i] != B[t]) :
      x = B[t]
      B[t] = B[i]
      B[i] = x
      t -= 1
    else:
      print("No")
      quit()
  

print("Yes")  
for i in range(N):
  print(B[i], end = " ")
print("")

Solution (Python):
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()][::-1]

ng = []
for i in range(n):
    if a[i] == b[i]:
        ng.append(i)

if len(ng) == 0:
    print('Yes')
    print(*b)
    sys.exit()

min_ng = min(ng)
max_ng = max(ng)

left = 0
right = n - 1

for i in ng:
    if b[i] != b[left] and a[left] != b[i]:
        b[i], b[left] = b[left], b[i]
        left += 1
        continue
    if b[i] != b[right] and a[right] != b[i]:
        b[i], b[right] = b[right], b[i]
        right -= 1

flag = 1

for i in range(n):
    if a[i] == b[i]:
        flag = 0

if flag:
    print('Yes')
    print(*b)
else:
    print('No')

Solution (Python):
from heapq import heappush, heappop


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

all_freq = {}

cnt_b = [0] * 220000
for num in b:cnt_b[num] += 1


for num in a:
    if num not in all_freq:
        all_freq[num] = 0
    all_freq[num] += 1

for num in b:
    if num not in all_freq:
        all_freq[num] = 0
    all_freq[num] += 1

heap = []

for num, freq in all_freq.items():
    if freq > n:
        print("No")
        exit()
    if cnt_b[num] > 0:
        heappush(heap, (-freq, num))

ans = []

def get_max():
    (freq, num) = heappop(heap)
    freq = -freq
    while all_freq[num] != freq:
        (freq, num) = heappop(heap)
        freq = -freq

    return num

for num in a:
    most_freq_num = get_max()
    if most_freq_num != num:
        ans.append(most_freq_num)
        all_freq[most_freq_num] -= 1
        cnt_b[most_freq_num] -= 1
        if cnt_b[most_freq_num] > 0:
            heappush(heap, (-all_freq[most_freq_num], most_freq_num))
    else:
        second_freq_num = get_max()
        heappush(heap, (-all_freq[most_freq_num], most_freq_num))
        ans.append(second_freq_num)
        all_freq[second_freq_num] -= 1
        cnt_b[second_freq_num] -= 1
        if cnt_b[second_freq_num] > 0:
            heappush(heap, (-all_freq[second_freq_num], second_freq_num))
    all_freq[num] -= 1
    if cnt_b[num] == 0:continue
    heappush(heap, (-all_freq[num], num))

print("Yes")
print(*ans)

Solution (Python):
from collections import Counter, deque

(N,) = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]

freqA = Counter(A)
freqB = Counter(B)
for k in freqA.keys() & freqB.keys():
    if freqA[k] + freqB[k] > N:
        print("No")
        exit()

B = deque(B)
while True:
    rotate = 0
    for i in range(N):
        while A[(i + rotate) % N] == B[i]:
            rotate += 1
    bad = False
    B.rotate(rotate)
    for a, b in zip(A, B):
        if a == b:
            bad = True
    if not bad:
        break

print("Yes")
print(" ".join(map(str, B)))

Solution (Python):
def LI():return list(map(int,input().split()))
def II():return int(input())
def yes():return print("Yes")
def no():return print("No")
INF=float("inf")
from collections import deque, Counter
from heapq import heappop, heappush
from itertools import product, combinations
from functools import reduce, lru_cache
from math import pi, gcd
from decimal import Decimal





























































































n=II()
a=LI()
b=LI()
c=b[::-1]
bb=deque(b)
ac=Counter(a)
bc=Counter(b)

for i in range(n):
    if ac[i]+bc[i]>n:
        print("No")
        exit()

import time

t1=time.time()
for i in range(10000000):
    if time.time()-t1>1.5:
        print("No")
        exit()        
    tmp=bb.popleft()
    bb.append(tmp)
    if any(d==e for d,e in zip(a,bb)):
        continue
    print("Yes")
    print(*bb)
    exit()

Solution (Python):

import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys


readline = sys.stdin.readline

INF = 1 << 60


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A, B):
    B.reverse()
    
    

    ng = []
    ngi = set()
    for i, (a, b) in enumerate(zip(A, B)):
        if a == b:
            ng.append((i, a, b))


    for i in range(N):
        if not ng:
            break
        if i != ng[-1][0] and B[i] != ng[-1][2] and A[i] != ng[-1][1]:
            j, a, b = ng.pop()
            B[i], B[j] = B[j], B[i]



    if all(map(lambda x: x[0] != x[1], zip(A, B))):
        print('Yes')
        print(*B)
    else:
        print('No')


def main():
    N = read_int()
    A = read_int_n()
    B = read_int_n()
    (slv(N, A, B))


if __name__ == '__main__':
    main()

Solution (Python):

class segment_tree:
    def __init__(self, N, operator_M, e_M):
        self.op_M = operator_M
        self.e_M = e_M
        
        self.N0 = 1<<(N-1).bit_length()
        self.dat = [self.e_M]*(2*self.N0)
    
    
    def build(self, initial):
        self.dat[self.N0:self.N0+len(initial)] = initial[:]
        for k in range(self.N0-1,0,-1):
            self.dat[k] = self.op_M(self.dat[2*k], self.dat[2*k+1])

    
    def update(self,k,x):
        k += self.N0
        self.dat[k] = x
        k //= 2
        while k:
            self.dat[k] = self.op_M(self.dat[2*k], self.dat[2*k+1])
            k //= 2

    
    def query(self,L,R):
        L += self.N0; R += self.N0 + 1 
        sl = sr = self.e_M
        while L < R:
            if R & 1:
                R -= 1
                sr = self.op_M(self.dat[R],sr)
            if L & 1:
                sl = self.op_M(sl,self.dat[L])
                L += 1
            L >>= 1; R >>= 1
        return self.op_M(sl,sr)

    def get(self, k): 
        return self.dat[k+self.N0]



import sys
readline = sys.stdin.readline
read = sys.stdin.read

n, = map(int,readline().split())
*a, = map(int,readline().split())
*b, = map(int,readline().split())

ca = [0]*(n+1)
cb = [0]*(n+1)

for i in a: ca[i] += 1
for i in b: cb[i] += 1


from heapq import *

qc = [0]*(n+1)
for i,(x,y) in enumerate(zip(ca,cb)):
    if x+y > n:
        print("No")
        exit()
    elif i==0 or x+y==0:
        continue
    else:
        qc[i] = x+y


def op(a,b):
    if qc[a] <= qc[b]: return b
    else: return a

s = segment_tree(n+1,op,0)
s.build(list(range(n+1)))

sa = set(a)
sb = set(b)

def dela(j):
    ca[j] -= 1
    if ca[j]==0:
        sa.remove(j)
    
def delb(j):
    cb[j] -= 1
    if cb[j]==0:
        sb.remove(j)

ans = [None]*n
for i in range(n):
    j = s.dat[1]
    
    
    if ca[j]:
        dela(j)

        for k in sb:
            if k != j: break
        delb(k)
        ans[i] = (j,k)

    else:
        delb(j)
        
        for k in sa:
            if k != j: break
        dela(k)
        ans[i] = (k,j)
    
    qc[j] -= 1
    qc[k] -= 1
    s.update(j,j)
    s.update(k,k)

from operator import itemgetter
ans.sort(key=itemgetter(0))

print("Yes")
ans = [y for x,y in ans]
print(*ans)

Solution (Python):
N = int(input())

A_list = list(map(int, input().split()))
B_list = list(map(int, input().split()))

total_table = {}

def make_table(l):
	table = {}
	for v in l:
		if v in table:
			table[v] += 1
		else:
			table[v] = 1
		if v in total_table:
			total_table[v] += 1
		else:
			total_table[v] = 1
	return table

A_table = make_table(A_list)
B_table = make_table(B_list)

total_list = []
for v, c in total_table.items():
	total_list.append((c, v))

total_list.sort()
total_list.reverse()

A_head = []
A_tail = []
B_head = []
B_tail = []
for c, v in total_list:
	a = A_table[v] if v in A_table else 0
	b = B_table[v] if v in B_table else 0

	while a > 0 and len(A_head) + len(B_head) < N:
		A_head.append(v)
		a -= 1
	
	while b > 0 and len(A_head) + len(B_head) < N:
		B_head.append(v)
		b -= 1
	
	while a > 0:
		A_tail.append(v)
		a -= 1
	
	while b > 0:
		B_tail.append(v)
		b -= 1






A_tail.reverse()
B_head.reverse()

A_list = A_head + A_tail
B_list = B_tail + B_head




def check():
	for a, b in zip(A_list, B_list):
		if a == b:
			return False
	else:
		return True

if check():
	AB_list = list(zip(A_list, B_list))
	AB_list.sort()
	print("Yes")
	print(*(b for a, b in AB_list))
else:
	print("No")

Solution (Python):
from collections import Counter
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
AC = Counter(A)
BC = Counter(B)
for i in BC.keys():
    if i in AC and BC[i] + AC[i] > N:
        print("No")
        exit()
AL,AR = {},{} 
BL,BR = {},{}
for i in range(N):
    if not A[i] in AL:
        AL[A[i]] = i
    AR[A[i]] = i

for i in range(N):
    if not B[i] in BL:
        BL[B[i]] = i
    BR[B[i]] = i
can = [1]*(N)

for i in BL.keys():
    if not i in AL:
        continue
    s = (N+AL[i]-BR[i])%N
    e = (N+AR[i]-BL[i])%N
    if e<s:
        e += N
    
    for j in range(s,e+1):
        can[j%N] = 0

if 1 in can:
    print("Yes")
    ind = can.index(1)
    print(* (B+B)[N-ind:2*N-ind])
else:
    print("No")