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 collections
import sys

def solve(n, A, B):
  ans = B[:]
  same = collections.deque()
  for i, (a, b) in enumerate(zip(A, B)):
    if a == b:
      if same and B[same[0]] != a:
        j = same.popleft()
        B[i], B[j] = B[j], B[i]
      else:
        same.append(i)
 
  
  
  if same:
    s = A[same[0]]
    to_swap = []
    possible = False
    for i, (a, b) in enumerate(zip(A, B)):
      if a != s and b!=s:
        to_swap.append(i)
      if len(to_swap) == len(same):
        possible = True
        break
    if not possible:
      print('No')
      return
    for i, j in zip(same, to_swap):
      B[i], B[j] = B[j], B[i]
  print('Yes')
  print(' '.join(map(str, B)) )


       


def main():
  input = sys.stdin.readline
  n = int(input())
  A = list(map(int, input().split()))
  B = list(map(int, input().split()))
  solve(n, A, B)

main()

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

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

c = [0] * (n + 1)
d = [0] * (n + 1)
for i in range(n):
    c[a[i]] += 1
    d[b[i]] += 1


for i in range(n + 1):
    if c[i] + d[i] > n:
        print('No')
        sys.exit(0)

import itertools
c = list(itertools.accumulate(c))
d = list(itertools.accumulate(d))

max_gap = 0
for i in range(1, n + 1):
    max_gap = max(max_gap, c[i] - d[i-1])

ans = [0] * n
for i in range(n):
    ans[(i + max_gap) % n] = str(b[i])

print('Yes')
print(' '.join(ans))

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
cnta = [0]*(n+1)
cntb = [0]*(n+1)
ta = 0
tb = 0
s = [0]*(n+1)
for i in range(n):
    cnta[a[i]] += 1
    cntb[b[i]] += 1
    s[a[i]] += 1
    s[b[i]] += 1
if max(s) > n:
    print("No")
    exit()
print("Yes")
m = 0
for i in range(1,n+1):
    cnta[i] += cnta[i-1]
    cntb[i] += cntb[i-1]
for i in range(1,n+1):
    m = max(m,cnta[i]-cntb[i-1])



print(*b[-m:]+b[0:-m])

Solution (Python):
from collections import defaultdict
dic = defaultdict(int)
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
for x,y in zip(A,B):
  dic[x] += 1
  dic[y] += 1
L = list(dic.values())
MAX = max(L)
if MAX > N:
  print("No"); exit()
INF = float("inf")
dicA_min = defaultdict(lambda: INF); dicA_max = defaultdict(lambda: 0)
dicB_min = defaultdict(lambda: INF); dicB_max = defaultdict(lambda: 0)
for i in range(N):
  dicA_min[A[i]] = min(dicA_min[A[i]],i)
  dicA_max[A[i]] = max(dicA_max[A[i]],i)
  dicB_min[B[i]] = min(dicB_min[B[i]],i)
  dicB_max[B[i]] = max(dicB_max[B[i]],i)

L = list(dicB_min.keys())
mink = -INF
maxk = INF
Flag = False
for t in L:
  if dicA_min[t] == INF:
    continue
  mink = max(dicA_max[t]-dicB_min[t]+1,mink)
  maxk = min(dicA_min[t]+N-dicB_max[t]-1,maxk)
  Flag = True
if not Flag:
  print("Yes")
  print(*B)
  exit()

if mink >= 0:
  ans = B[-mink:] + B[:-mink]
else:
  ans = B[-mink:] + B[:-mink]
print("Yes")
print(*ans)

Solution (Python):
import sys

input=sys.stdin.buffer.readline





def RD(): return sys.stdin.read()


def II(): return int(input())


def MI(): return map(int,input().split())


def MF(): return map(float,input().split())


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


def LF(): return list(map(float,input().split()))


def TI(): return tuple(map(int,input().split()))



import numpy as np

def main():
	n=II()
	A=np.array([0]+LI()+[10**6])
	B=np.array([0]+LI()+[10**6])
	Ar=(A[:-1]<A[1:])[1:]
	Al=(A[:-1]<A[1:])[:-1]
	Br=(B[:-1]<B[1:])[1:]
	Bl=(B[:-1]<B[1:])[:-1]
	
	A=A[1:-1]
	B=B[1:-1]
	
	
	
	AAl=np.array([10**7]*(n+1))
	AAr=np.array([10**7]*(n+1))
	BBl=np.array([-10**7]*(n+1))
	BBr=np.array([-10**7]*(n+1))
	
	for i in range(n):
		if Al[i]==1:
			AAl[A[i]]=i
		if Ar[i]==1:
			AAr[A[i]]=i
		if Bl[i]==1:
			BBl[B[i]]=i
		if Br[i]==1:
			BBr[B[i]]=i
	
	L=AAl-BBr
	R=AAr-BBl
	R=R[R<10**6]
	
	LL=L.min()
	
	try:
		RR=max(R)
	except:
		RR=0
	
	
	
	if RR-LL+2>n:
		print("No")
	else:
		print("Yes")
		C=np.concatenate([B[-LL+1:],B[:-LL+1]])
		print(*C)
	
	


	









if __name__=="__main__":
	main()

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
b.reverse()
p = 1
c = 0
d = 0
for i in range(n):
    if a[i] == b[i]:
        v = a[i]
        h = i
        p = 0
        break
if p == 1:
    print('Yes')
    for i in range(n):
        print(b[i],end = ' ')
else:
    for i in range(n):
        if a[i] != v and b[i] != v:
            c += 1
        if b[i] == a[i] :
            d += 1
    if c < d:
        print('No')
    else:
        print('Yes')
        o = 0
        for i in range(n):
            if a[i] != v and b[i] != v:
                b[i],b[h+o] = b[o+h],b[i]
                o += 1
                if o == d:
                    break
        for i in range(n):
            print(b[i],end = ' ')

Solution (Python):


import collections
import sys
input=sys.stdin.readline

n=int(input())
arr1=list(map(int,input().split()))
arr2=list(map(int,input().split()))
cnt1=collections.Counter(arr1)
cnt2=collections.Counter(arr2)
tmp=[[key,cnt1[key]] for key in cnt1.keys()]
tmp=sorted(tmp,reverse=True,key=lambda x:x[1])
arr3=[]
for key,cnt in tmp:
    for _ in range(cnt):
        arr3.append(key)
cnt1=collections.Counter(arr3)
ans=[0]*n
acum=0
pos=0
blank=0
ok=0
head=[]
for key in cnt1.keys():
    tcnt1=cnt1[key]
    tcnt2=cnt2[key]
    acum+=tcnt1
    tpos=max(acum,pos)
    tmp=n-min(tpos,n)
    if blank+tmp<tcnt2:
        print('No')
        exit()
    blank=min(tpos,n)-ok
    remain=tcnt2
    
    for i in range(tpos,n):
        if remain==0:
            break
        ans[i]=key
        ok+=1
        remain-=1
        cnt2[key]-=1
    for _ in range(remain):
        head.append(key)
        cnt2[key]-=1
    pos=min(tpos+tcnt2,n)
    
for key in cnt2.keys():
    if cnt2[key]==0:
        continue
    for _ in range(cnt2[key]):
        head.append(key)
pos=0
for i in range(n):
    if ans[i]==0:
        ans[i]=head[pos]
        pos+=1
tmp=[[ans[i],arr3[i]] for i in range(n)]
tmp=sorted(tmp,key=lambda x:x[1])
ans=[tmp[i][0] for i in range(n)]
print('Yes')
print(*ans)

Solution (Python):


import heapq
import collections
import sys
input=sys.stdin.readline

n=int(input())
arr1=list(map(int,input().split()))
arr2=list(map(int,input().split()))
cnt1=collections.Counter(arr1)
cnt2=collections.Counter(arr2)
tmp=[[key,cnt1[key]] for key in cnt1.keys()]
tmp=sorted(tmp,reverse=True,key=lambda x:x[1])
arr3=[]
for key,cnt in tmp:
  for _ in range(cnt):
    arr3.append(key)
cnt3=collections.Counter(arr3)
ans=[0]*n
acum=0
pos=0
head=[]
tail=[]
for key in cnt3.keys():
    tcnt1=cnt3[key]
    tcnt2=cnt2[key]
    if tcnt1+tcnt2>n:
        print('No')
        exit()
    acum+=tcnt1
    tpos=max(acum,pos)
    remain=tcnt2
    
    for i in range(tpos,n):
        if remain==0:
            break
        ans[i]=key
        remain-=1
        cnt2[key]-=1
    for _ in range(remain):
      if tpos!=pos:
        head.append(key)
      else:
        tail.append(key)
      cnt2[key]-=1
    pos=min(tpos+tcnt2,n)
    
for key in cnt2.keys():
    if cnt2[key]==0:
        continue
    for _ in range(cnt2[key]):
        tail.append(key)
pos=0
head+=tail
for i in range(n):
    if ans[i]==0:
        ans[i]=head[pos]
        pos+=1
q=[]
for i in range(n):
  heapq.heappush(q,(arr3[i],ans[i]))
for i in range(n):
  _,val=heapq.heappop(q)
  ans[i]=val
print('Yes')
print(*ans)

Solution (Python):
n = int(input()); a = list(map(int, input().split())); b = list(map(int, input().split()))
c = [0]*n; d = [0]*n; g = 0
for i in range(n): c[a[i]-1] += 1; d[b[i]-1] += 1
for i in range(n): g = max(g, c[i]+d[i])
e = [c[0]]; f = [d[0]]; h = e[0]
for i in range(1, n): e.append(c[i]+e[-1]); f.append(d[i]+f[-1])
for i in range(n-1): h = max(h, e[i+1]-f[i])
if g > n: print("No")
else: print("Yes"); print(*(b[n-h:]+b[:n-h]))

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline

N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
cntA = [0] * (N + 1)
cntB = [0] * (N + 1)
for i in range(N):
    cntA[A[i]] += 1
    cntB[B[i]] += 1
nums = [(cntA[i], cntB[i], i) for i in range(1, N+1) if cntA[i] or cntB[i]]
nums.sort(key=lambda p: p[0] + p[1], reverse=True)
a = deque()
b = deque()
c = deque(list(range(N)))
ansa = [0] * N
ansb = [0] * N
for x, y, n in nums:
    if x + y > len(a) + len(b) + len(c):
        print('No')
        exit()
    ra = x - len(a)
    rb = y - len(b)
    for i in range(ra):
        ansa[c[0]] = n
        b.append(c[0])
        c.popleft()
        x -= 1
    for i in range(rb):
        ansb[c[0]] = n
        a.append(c[0])
        c.popleft()
        y -= 1
    while c and (x or y):
        if x:
            ansa[c[0]] = n
            b.append(c[0])
            x -= 1
        else:
            ansb[c[0]] = n
            a.append(c[0])
            y -= 1
        c.popleft()
    for i in range(x):
        ansa[a[0]] = n
        a.popleft()
    for i in range(y):
        ansb[b[0]] = n
        b.popleft()
ans = [(ansa[i], ansb[i]) for i in range(N)]
ans.sort()
print('Yes')
print(*[p[1] for p in ans])

Solution (Python):
from collections import Counter
from heapq import heapify, heappop, heappush
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))
    idx_a[a] = i
    cnt_a[a] = cnt
    i += cnt

cnt_b = Counter(bbb)
hq_both = []
hq_free = []
for a, ca in cnt_a.items():
    if a in cnt_b:
        hq_both.append((-(ca + cnt_b[a]), a))
    else:
        hq_free.append(a)
heapify(hq_both)



ans = [-1] * n
remaining = n

while hq_both:
    cab, a1 = heappop(hq_both)
    cab = -cab
    assert cab == cnt_a[a1] + cnt_b[a1]

    

    if cab > remaining:
        print('No')
        exit()

    cb = cnt_b[a1]
    while cb:
        if hq_both:
            _, a2 = heappop(hq_both)
            pop_from_que = True
        else:
            a2 = hq_free.pop()
            pop_from_que = False
        ca = cnt_a[a2]
        
        if ca <= cb:
            l = idx_a[a2]
            ans[l:l + ca] = [a1] * ca
            remaining -= ca
            idx_a[a2] += ca
            cnt_a[a2] -= ca
            cnt_b[a1] -= ca
            cb -= ca
        else:
            l = idx_a[a2]
            ans[l:l + cb] = [a1] * cb
            remaining -= cb
            idx_a[a2] += cb
            cnt_a[a2] -= cb
            cnt_b[a1] -= cb
            cb = 0
            if pop_from_que:
                heappush(hq_both, (-(cnt_a[a2] + cnt_b[a2]), a2))
            else:
                hq_free.append(a2)
        
    hq_free.append(a1)

for b, cb in cnt_b.items():
    if cb == 0:
        continue
    while cb:
        a = hq_free.pop()
        ca = cnt_a[a]
        if ca <= cb:
            l = idx_a[a]
            ans[l:l + ca] = [b] * ca
            cb -= ca
        else:
            l = idx_a[a]
            ans[l:l + cb] = [b] * cb
            idx_a[a] += cb
            cnt_a[a] -= cb
            cb = 0
            hq_free.append(a)

print('Yes')
print(*ans)

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline

N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
cntA = [0] * (N + 1)
cntB = [0] * (N + 1)
for i in range(N):
    cntA[A[i]] += 1
    cntB[B[i]] += 1
nums = [(cntA[i], cntB[i], i) for i in range(1, N+1)]
nums.sort(key=lambda p: p[0] + p[1], reverse=True)
a = deque()
b = deque()
c = deque(list(range(N)))
ansa = [0] * N
ansb = [0] * N
for x, y, n in nums:
    if x == y == 0:
        break
    if x + y > len(a) + len(b) + len(c):
        print('No')
        exit()
    ra = x - len(a)
    rb = y - len(b)
    for i in range(ra):
        ansa[c[0]] = n
        b.append(c[0])
        c.popleft()
        x -= 1
    for i in range(rb):
        ansb[c[0]] = n
        a.append(c[0])
        c.popleft()
        y -= 1
    while c and (x or y):
        if x:
            ansa[c[0]] = n
            b.append(c[0])
            x -= 1
        else:
            ansb[c[0]] = n
            a.append(c[0])
            y -= 1
        c.popleft()
    for i in range(x):
        ansa[a[0]] = n
        a.popleft()
    for i in range(y):
        ansb[b[0]] = n
        b.popleft()
ans = []
for i in range(N):
    ans.append((ansa[i], ansb[i]))
ans.sort()
print('Yes')
print(*[p[1] for p in ans])

Solution (Python):


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())

from collections import Counter
d = Counter(a+b)
if max(d.values()) > n:
    print("No")
    exit()

same = set(i for i in range(n) if a[i]==b[i])
from random import randrange
while same:
    i = same.pop()
    while True:
        j = randrange(0,n)
        if a[j] != b[i] and a[i] != b[j]:
            b[i],b[j] = b[j],b[i]
            same.discard(j)
            break

print("Yes")
print(*b)

Solution (Python):


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())
b = b[::-1]
from collections import Counter
d = Counter(a+b)
if max(d.values()) > n:
    print("No")
    exit()

same = set(i for i in range(n) if a[i]==b[i])
from random import randrange
while same:
    i = same.pop()
    while True:
        j = randrange(0,n)
        if a[j] != b[i] and a[i] != b[j]:
            b[i],b[j] = b[j],b[i]
            same.discard(j)
            break

print("Yes")
print(*b)

Solution (Python):
import sys
from collections import Counter

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c for j in range(b)] for i in range(a)]
def list3d(a, b, c, d): return [[[d for k in range(c)] for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e for l in range(d)] for k in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10**9)
INF = 10**19
MOD = 10**9 + 7
EPS = 10**-10

N = INT()
A = LIST()
B = LIST()

C1 = Counter(A)
C2 = Counter(B)
for k, v in C1.items():
    if v > N-C2[k]:
        No()
        exit()

ans = B[ceil(N, 2):] + B[:ceil(N, 2)]

def check(A, B):
    for i in range(N):
        if A[i] == B[i]:
            return i
    return -1

def swap(x, A, B):
    for i in range(N):
        if A[x] != B[i] and A[i] != B[x]:
            B[x], B[i] = B[i], B[x]
            return True
    return False

while 1:
    res = check(A, ans)
    if res == -1:
        Yes()
        print(*ans)
        break
    else:
        if not swap(res, A, ans):
            No()
            break

Solution (Python):
import sys
input = sys.stdin.readline

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

from collections import Counter

CA=Counter(A)
CB=Counter(B)

H=[]

for ca in CA:
    if CA[ca]>0 and CB[ca]>0:
        if CA[ca]+CB[ca]>N:
            print("No")
            sys.exit()
        H.append((-(CA[ca]+CB[ca]),ca))

import heapq
heapq.heapify(H)

ANSDICT=dict()

while len(H)>=2:
    c1,x1=heapq.heappop(H)
    c1=-c1

    c2,x2=heapq.heappop(H)
    c2=-c2

    if x1 in ANSDICT:
        ANSDICT[x1].append(x2)
    else:
        ANSDICT[x1]=[x2]

    if x2 in ANSDICT:
        ANSDICT[x2].append(x1)
    else:
        ANSDICT[x2]=[x1]

    CA[x1]-=1
    CA[x2]-=1
    CB[x1]-=1
    CB[x2]-=1

    if CA[x1]>0 and CB[x1]>0:
        heapq.heappush(H,(-(c1-2),x1))

    if CA[x2]>0 and CB[x2]>0:
        heapq.heappush(H,(-(c2-2),x2))

ANS=[-1]*N

for i in range(N):
    a=A[i]
    if a in ANSDICT and len(ANSDICT[a])!=0:
        
        x=ANSDICT[a].pop()
        ANS[i]=x

if H:
    cc,xx=H[0]
    cc=-cc

    for i in range(N):
        if ANS[i]==-1 and A[i]!=xx:
            ANS[i]=xx
            CB[xx]-=1

            if CB[xx]==0:
                break

ind=0
for cb in CB:
    while CB[cb]!=0:
        while ANS[ind]!=-1:
            ind+=1
        ANS[ind]=cb
        CB[cb]-=1

print("Yes")
print(*ANS)

Solution (Python):
N, = map(int, input().split())
X = list(map(int, input().split()))
Y = list(map(int, input().split()))[::-1]
on = []
z = 0
for i in range(N):
    if not X[i]-Y[i]:
        on.append(i)
        z = X[i]
for i in range(N):
    if X[i]!=z and Y[i] != z and on:
        j = on.pop()
        Y[i], Y[j] = Y[j], Y[i]
if on:
    print("No")
else:
    print("Yes")
    print(*Y)

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline

N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
cntA = [0] * (N + 1)
cntB = [0] * (N + 1)
for i in range(N):
    cntA[A[i]] += 1
    cntB[B[i]] += 1
nums = [(cntA[i], cntB[i], i) for i in range(1, N+1)]
nums.sort(key=lambda p: p[0] + p[1], reverse=True)
a = deque()
b = deque()
c = deque(list(range(N)))
ansa = [0] * N
ansb = [0] * N
for x, y, n in nums:
    if x == y == 0:
        break
    if x + y > len(a) + len(b) + len(c):
        print('No')
        exit()
    if x + y <= len(c):
        for i in range(x):
            ansa[c[0]] = n
            b.append(c[0])
            c.popleft()
        for i in range(y):
            ansb[c[0]] = n
            a.append(c[0])
            c.popleft()
    else:
        ra = x - len(a)
        rb = y - len(b)
        if ra > 0:
            for i in range(ra):
                ansa[c[0]] = n
                b.append(c[0])
                c.popleft()
            x -= ra
        if rb > 0:
            for i in range(rb):
                ansb[c[0]] = n
                a.append(c[0])
                c.popleft()
            y -= rb
        while len(c):
            if x:
                ansa[c[0]] = n
                b.append(c[0])
                x -= 1
            else:
                ansb[c[0]] = n
                a.append(c[0])
                y -= 1
            c.popleft()
        for i in range(x):
            ansa[a[0]] = n
            a.popleft()
        for i in range(y):
            ansb[b[0]] = n
            b.popleft()
ans = []
for i in range(N):
    ans.append((ansa[i], ansb[i]))
ans.sort()
print('Yes')
print(*[p[1] for p in ans])

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s = 0
c = True
for i in range(n):
    if i > 0:
        if a[i] != a[i-1]:
            s = 0
    if a[i] != b[i]:
        continue
    else:
        c = False
        while s != n:
            if a[i] != b[s] and a[s] != b[i]:
                b[i], b[s] = b[s], b[i]
                c = True
                break
            s += 1
        if not c:
            break
if not c:
    print("No")
else:
    print("Yes")
    print(*b)

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

count = [0] * (N+1)
for a, b in zip(A, B):
    count[a] += 1
    count[b] += 1

for i in range(N+1):
    if count[i] > N:
        print('No')
        quit()

diff = 0
checked = set()
ida = 0
for i, b in enumerate(B):
    if b in checked:
        continue
    checked.add(b)
    while ida < N and A[ida] <= b:
        ida += 1
    diff = max(diff, ida - i)


print('Yes')
print(*(B[-diff:]+B[:-diff]))

Solution (Python):
import collections
import sys

def solve(n, A, B):
  Ac = collections.defaultdict(int)
  ABc =  collections.defaultdict(int)
  for a in A:
    Ac[a] = 1 + Ac.get(a, 0)
    ABc[a] = 1 + ABc.get(a, 0)
  Bc =  collections.defaultdict(int)
  for b in B:
    Bc[b]  = 1 + Bc.get(b, 0)
    ABc[b] = 1 + ABc.get(b, 0)
  cAB = sorted([(c, ab) for ab, c in ABc.items()])
  
  pool = collections.deque()  

  matched = {}  
  current = n   
  for c, ab in cAB[::-1]:
    if c > current + len(pool):
      print('No')
      return
    matched[ab] = []
    while c > current:
      
      c -= 1
      matched[ab].append(pool.popleft())
    
    current -= Bc[ab]
    for _ in range(Bc[ab]):
      pool.append(ab)
  
  skipped = []
  for c, ab in cAB:
    
    nn = Ac[ab]-len(matched[ab])
    while skipped and  Ac[ab]-len(matched[ab]) > 0:
      matched[ab].append(skipped.pop())
    while Ac[ab]-len(matched[ab]) > 0:
      p = pool.popleft()
      if p == ab:
        skipped.append(p)
      else:
        matched[ab].append(p)
   

  ans = []
  for a, bb in sorted(matched.items()):
    ans += [str(b) for b in bb]
  print('Yes')
  print(' '.join(ans))


def main():
  input = sys.stdin.readline
  n = int(input())
  A = list(map(int, input().split()))
  B = list(map(int, input().split()))
  solve(n, A, B)

main()

Solution (Python):
import collections
import sys

def solve(n, A, B):
  Ac = collections.defaultdict(int)
  ABc = collections.defaultdict(int)
  Bc = collections.defaultdict(int)
  for a in A:
    Ac[a] = 1 + Ac.get(a, 0)
    ABc[a] = 1 + ABc.get(a, 0)
    
  for b in B:
    
    Bc[b]  = 1 + Bc.get(b, 0)
    ABc[b] = 1 + ABc.get(b, 0)
  cAB = sorted([(c, ab) for ab, c in ABc.items()])
  
  pool = collections.deque()  

  matched = {}  
  current = n   
  for c, ab in cAB[::-1]:
    if c > current + len(pool):
      print('No')
      return
    matched[ab] = []
    while c > current:
      
      c -= 1
      matched[ab].append(pool.popleft())
    
    current -= Bc[ab]
    for _ in range(Bc[ab]):
      pool.append(ab)
  
  skipped = []
  for c, ab in cAB:
    
    nn = Ac[ab]-len(matched[ab])
    while skipped and  Ac[ab]-len(matched[ab]) > 0:
      matched[ab].append(skipped.pop())
    while Ac[ab]-len(matched[ab]) > 0:
      p = pool.popleft()
      if p == ab:
        skipped.append(p)
      else:
        matched[ab].append(p)
      

  ans = []
  for a, bb in sorted(matched.items()):
    ans += [str(b) for b in bb]
  print('Yes')
  print(' '.join(ans))


def main():
  input = sys.stdin.readline
  n = int(input())
  A = list(map(int, input().split()))
  B = list(map(int, input().split()))
  solve(n, A, B)

main()

Solution (Python):
import collections
import sys

def solve(n, A, B):
  Ac = {}
  ABc = {}
  Bc = {}
  for a in A:
    Ac[a] = 1 + Ac.get(a, 0)
    ABc[a] = 1 + ABc.get(a, 0)
    Bc[a] = Bc.get(a, 0)
  for b in B:
    Ac[b] = Ac.get(b, 0)
    Bc[b]  = 1 + Bc.get(b, 0)
    ABc[b] = 1 + ABc.get(b, 0)
  cAB = sorted([(c, ab) for ab, c in ABc.items()])
  
  pool = collections.deque()  

  matched = {}  
  current = n   
  for c, ab in cAB[::-1]:
    if c > current + len(pool):
      print('No')
      return
    matched[ab] = []
    while c > current:
      
      c -= 1
      matched[ab].append(pool.popleft())
    
    current -= Bc[ab]
    for _ in range(Bc[ab]):
      pool.append(ab)
  
  skipped = []
  for c, ab in cAB:
    
    nn = Ac[ab]-len(matched[ab])
    while skipped and  Ac[ab]-len(matched[ab]) > 0:
      matched[ab].append(skipped.pop())
    while Ac[ab]-len(matched[ab]) > 0:
      p = pool.popleft()
      if p == ab:
        skipped.append(p)
      else:
        matched[ab].append(p)
      

  ans = []
  for a, bb in sorted(matched.items()):
    ans += [str(b) for b in bb]
  print('Yes')
  print(' '.join(ans))


def main():
  input = sys.stdin.readline
  n = int(input())
  A = list(map(int, input().split()))
  B = list(map(int, input().split()))
  solve(n, A, B)

main()

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 numpy as np

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

count = [0] * (N+1)
for a, b in zip(A, B):
    count[a] += 1
    count[b] += 1

for i in range(N+1):
    if count[i] > N:
        print('No')
        quit()

diff = 0
checked = set()
ida = 0
for i, b in enumerate(B):
    if b in checked:
        continue
    checked.add(b)
    while ida < N and A[ida] <= b:
        ida += 1
    diff = max(diff, ida - i)


idx = (np.arange(N) - diff) % N
print('Yes')
print(*np.array(B)[idx])

Solution (Python):


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())
b = b[::-1]

same = [i for i in range(n) if a[i] == b[i]]
if same:
    
    v = a[same[0]] 
    r = same[0]
    s = same[-1]+1
    vidx = [i for i in range(n) if a[i]==v or b[i]==v]
    p = vidx[0]
    q = vidx[-1]+1
    
    if q > n-s+r+p: 
        print("No")
        exit()
    
    if p >= s-r:
        b[r:s],b[:s-r] = b[:s-r],b[r:s]
    else:
        b[r:r+p],b[:p] = b[:p],b[r:r+p]
        b[r+p:s],b[n-s+r+p:] = b[n-s+r+p:], b[r+p:s]

print("Yes")
print(*b)

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

ac = [0]*(N+1)
bc = [0]*(N+1)

ok = True
for i in range(N):
    ac[A[i]] += 1
    bc[B[i]] += 1

d = 0
for i in range(1, N+1):
    if (ac[i]+bc[i]) > N:
        ok = False
        break
    ac[i] += ac[i-1]
    bc[i] += bc[i-1]
    d = max(d, ac[i]-bc[i-1])

if ok:
    print("Yes")
    print(*[B[(i-d) % N] for i in range(N)])
else:
    print("No")

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

ac = [0]*(N+1)
bc = [0]*(N+1)

ok = True
for i in range(N):
    ac[A[i]] += 1
    bc[B[i]] += 1

d = 0
for i in range(1, N+1):
    if (ac[i]+bc[i]) > N:
        ok = False
        break
    ac[i] += ac[i-1]
    bc[i] += bc[i-1]
    d = max(d, ac[i]-bc[i-1])

if ok:
    print("Yes")
    print(*[B[(i+N-d) % N] for i in range(N)])
else:
    print("No")

Solution (Python):
import collections

n=int(input())
arr1=list(map(int,input().split()))
arr2=list(map(int,input().split()))
cnt1=collections.Counter(arr1)
cnt2=collections.Counter(arr2)
acum1=[0]*(n+1)
acum2=[0]*(n+1)
for i in range(1,n+1):
  acum1[i]=acum1[i-1]+cnt1[i]
  acum2[i]=acum2[i-1]+cnt2[i]
rotate=0
for i in range(1,n+1):
  rotate=max(rotate,acum1[i]-acum2[i-1])
ans=[0]*n
for i in range(n):
  ans[(i+rotate)%n]=arr2[i]
for i in range(n):
  if arr1[i]==ans[i]:
    print('No')
    break
else:
  print('Yes')
  print(*ans)

Solution (Python):
n = int(input())
lst_a = [int(i) for i in input().split()]
lst_b = [int(i) for i in input().split()]
j = 0
flag = True
for i in range(n):
  if i > 0:
    if lst_a[i] != lst_a[i - 1]:
      j = 0
  if lst_a[i] != lst_b[i]:
    continue
  else:
    flag = False
    while j != n:
      if lst_a[i] != lst_b[j] and lst_a[j] != lst_b[i]:
        lst_b[i], lst_b[j] = lst_b[j], lst_b[i]
        flag = True
        break
      j += 1
    if not flag:
      break
if not flag:
  print('No')
else:
  print('Yes')
  lst_b = [str(i) for i in lst_b]
  print(' '.join(lst_b))

Solution (Python):
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

import random
n = inp()
a = inpl()
b = inpl()
c = [0] * (n+1)
for i in range(n):
    c[a[i]] += 1
    c[b[i]] += 1
if max(c) > n:
    print('No')
    quit()
q = deque([])
for i in range(n):
    if a[i] == b[i]:
        q.append(i)
while q:
    now = q.popleft()
    nx = random.randint(0,n-1)
    if a[now] != b[nx] and a[nx] != b[now]:
        b[now],b[nx] = b[nx],b[now]
    else: q.append(now)
print('Yes')
print(*b)

Solution (Python):

import sys,io,os,time
from collections import defaultdict
from collections import Counter
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"

input = sys.stdin.readline


n = int(input())
a = list(map(int , input().split()))
b = list(map(int , input().split()))
b = b[::-1]
c = -1
for i in range(n):
	if a[i] == b[i]:
		c = a[i]
		break
l = 0
for i in range(n):
	if a[i] == c and b[i] == c:
		l = i
		break
r = -1
for i in range(n-1,-1,-1):
	if a[i] == c and b[i] == c:
		r = i
		break
for i in range(n):
	if a[i] != c and b[i] != c and l<=r:
		b[i] , b[l] = b[l], b[i]
		l+=1

if l <= r:
	print("No")
	exit()
print("Yes")
print(*b)











'''


import collections,sys,threading
sys.setrecursionlimit(10**9)
threading.stack_size(10**8)



threading.Thread(target=solve).start()
'''

Solution (Python):
from collections import Counter
N = int(input())
As = input().split()
Bs = input().split()

allct = Counter(As + Bs)
if allct.most_common(1)[0][1] > N:
    print('No')
    exit()

lastInA = {}
firstInB = {}

for i, a in enumerate(As):
    lastInA[a] = i

for i, b in enumerate(Bs):
    if b not in firstInB:
        firstInB[b] = i

offset = 0
for k, v in lastInA.items():
    if k not in firstInB:
        continue
    tmp = v - firstInB[k] + 1
    offset = offset if offset > tmp else tmp

print('Yes')
print(' '.join(Bs[-offset:] + Bs[:-offset]))