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):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
d={}
for i in a:
  if i in d:
    d[i][0]+=1
  else:
    d[i]=[1,0]
for i in b:
  if i in d:
    d[i][0]+=1
    d[i][1]+=1
  else:
    d[i]=[1,1]
l=[]
for i in d:
  l.append([d[i][0],i,d[i][1]])
l.sort()
l.reverse()


if l[0][0]>n:
  print("No")
else:
  print("Yes")
  l.append(l[0])
  cc=0
  ansa=[]
  i=1
  while l[i][2]==0:
    i+=1
  j=i+1
  while j!=len(l) and l[j][2]==0:
    j+=1
  ic,jc=0,0
  for t in a:
    if t==l[0][1]:
      continue
    cc+=1
    if cc>n-l[0][0]:
      ansa.append(l[0][1])
    elif l[i][1]==t:
      ansa.append(l[j][1])
      jc+=1
      if jc==l[j][2]:
        j+=1
        while j!=len(l) and l[j][2]==0:
          j+=1
        jc=0
    else:
      ansa.append(l[i][1])
      ic+=1
      if ic==l[i][2]:
        i=j
        j+=1
        while j!=len(l) and l[j][2]==0:
          j+=1
        ic=jc
        jc=0
  ans=[]
  ii=0
  for t in a:
    if t==l[0][1]:
      ans.append(l[i][1])
      ic+=1
      if ic==l[i][2]:
        i=j
        j+=1
        while j!=len(l) and l[j][2]==0:
          j+=1
        ic=jc
        jc=0
    else:
      ans.append(ansa[ii])
      ii+=1
  print(" ".join(map(str,ans)))

Solution (Python):
import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N = int(readline())
    A = list(map(int, readline().split()))
    B = list(map(int, readline().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(1, N + 1):
        if C[i] + D[i] > N:
            print('No')
            return

    print('Yes')

    C = list(accumulate(C))
    D = list(accumulate(D))

    B.reverse()

    i = 0
    while i < N and A[i] != B[i]:
        i += 1

    if i == N:
        print(*B)
        return

    n = A[i]
    leftA = C[n - 1]
    rightA = C[n]
    leftB = N - D[n]
    rightB = N - D[n - 1]

    i1 = min(leftA, leftB)
    i2 = max(leftA, leftB)
    i3 = min(rightA, rightB)
    i4 = max(rightA, rightB)

    for i in range(i3 - i2):
        if i < i1:
            B[i], B[i + i2] = B[i + i2], B[i]
        else:
            B[i - i1 + i4], B[i + i2] = B[i + i2], B[i - i1 + i4]

    print(*B)
    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N = int(readline())
    A = list(map(int, readline().split()))
    B = list(map(int, readline().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(1, N + 1):
        if C[i] + D[i] > N:
            print('No')
            return

    print('Yes')

    C = list(accumulate(C))
    D = list(accumulate(D))

    B.reverse()

    i = 0
    while i < N and A[i] != B[i]:
        i += 1

    if i == N:
        print(*B)
        return

    n = A[i]
    leftA = C[n - 1]
    rightA = C[n]
    leftB = N - D[n]
    rightB = N - D[n - 1]

    i1 = min(leftA, leftB)
    i2 = max(leftA, leftB)
    i3 = min(rightA, rightB)
    i4 = max(rightA, rightB)

    c = 0
    for i in range(i1):
        if c == i3 - i2:
            break
        B[i], B[i2 + c] = B[i2 + c], B[i]
        c += 1

    for i in range(i4, N):
        if c == i3 - i2:
            break
        B[i], B[i2 + c] = B[i2 + c], B[i]
        c += 1

    print(*B)
    return


if __name__ == '__main__':
    main()

Solution (Python):
def solve():    
    n = int(input())
    a = list(map(int,input().split()))
    b = list(map(int,input().split()))
    b = b[::-1]
    
    l = []
    num = -1
    for i in range(n):
        if a[i] == b[i]:
            l.append(i)
            num = a[i]
    
    ind = 0
    for i in range(n):
        if b[i] != num and a[i] != num and ind < len(l):
            b[i], b[l[ind]] = b[l[ind]], b[i]
            ind += 1
    
    if ind < len(l):
        print('No')
    else:
        print('Yes')
        print(*b)
    
                        
if __name__ == "__main__":
    solve()

Solution (Python):


import sys
from heapq import *
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

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

q = []
onlyA = []
onlyB = []
for i in range(N+1):
    if countA[i] and countB[i]:
        heappush(q,(-countA[i]-countB[i],i))
        continue
    for _ in range(countA[i]):
        onlyA.append(i)
    for _ in range(countB[i]):
        onlyB.append(i)
        
heapify(q)

if q and -q[0][0] > N:
    print('No')
    sys.exit()
print('Yes')

ans = []

while q:
    _,x = heappop(q)
    if q:
        _,y = heappop(q)
        flag = True
    else:
        y = onlyB.pop()
        flag = False
    countA[x] -= 1 
    countB[y] -= 1
    ans.append((x,y))
    if countA[x]:
        heappush(q,(-countA[x]-countB[x],x))
    else:
        for _ in range(countB[x]):
            onlyB.append(x)
            
    if flag and countB[y]:
        heappush(q,(-countA[y]-countB[y],y))
    if flag and not countB[y]:
        for _ in range(countA[y]):
            onlyA.append(y)

while onlyA:
    x,y = onlyA.pop(),onlyB.pop()
    ans.append((x,y))

ans.sort()
X,Y = zip(*ans)
print(*Y)

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)
if N < max((AC + BC).values()):
    print('No')
    exit()

curA = 0
curB = 0
while curA < N:
    a = A[curA]
    if a == B[curA]:
        while a == B[curB] or A[curB] == B[curA]:
            curB += 1
            curB %= N
        B[curA], B[curB] = B[curB], B[curA]
    curA += 1

print('Yes')
print(*B)

Solution (Python):
from collections import Counter
from heapq import heappush, heappop, heapreplace


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

AC = Counter(A)
BC = Counter(B)
S = AC + BC

q = []
for k, v in S.items():
    heappush(q, (-v, k))

ans = []
while q:
    v, k = q[0]
    if v == 0:
        heappop(q)
    elif v != -S[k]:
        heapreplace(q, (-S[k], k))
    else:
        heapreplace(q, (v + 1, k))
        if -v > N:
            print('No')
            exit()
        else:
            if AC[k] > 0:
                a = k
                for l in BC.keys():
                    if l != k:
                        b = l
                        break
            else:
                b = k
                for l in AC.keys():
                    if l != k:
                        a = l
                        break
            ans.append((a, b))
            S[a] -= 1; S[b] -= 1
            AC[a] -= 1; BC[b] -= 1
            if AC[a] == 0:
                AC.pop(a)
            if BC[b] == 0:
                BC.pop(b)

print('Yes')
X = [b for _, b in sorted(ans)]
print(*X)

Solution (Python):
from collections import Counter
from heapq import heappush, heappop, heapreplace


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

AC = Counter(A)
BC = Counter(B)
S = AC + BC

q = []
for k, v in S.items():
    heappush(q, (-v, k))

ans = []
while q:
    v, k = q[0]
    v = -v
    if v == 0:
        heappop(q)
    elif v != S[k]:
        heapreplace(q, (-S[k], k))
    else:
        heapreplace(q, (-(v - 1), k))
        if v > N:
            print('No')
            exit()
        else:
            if AC[k] > 0:
                a = k
                for l in BC.keys():
                    if l != k:
                        b = l
                        break
            else:
                b = k
                for l in AC.keys():
                    if l != k:
                        a = l
                        break
            ans.append((a, b))
            S[a] -= 1
            S[b] -= 1
            AC[a] -= 1
            if not AC[a]:
                AC.pop(a)
            BC[b] -= 1
            if not BC[b]:
                BC.pop(b)

print('Yes')
ans.sort()
X = [b for a, b in ans]
print(*X)

Solution (Python):
from collections import Counter
from heapq import heappush, heappop


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

AC = Counter(A)
BC = Counter(B)
S = AC + BC

q = []
for k, v in S.items():
    heappush(q, (-v, k))

ans = []
while q:
    v, k = heappop(q)
    v = -v
    if v != S[k]:
        if S[k] != 0:
            heappush(q, (-S[k], k))
    else:
        if v != 1:
            heappush(q, (-(v - 1), k))
        if v > N:
            print('No')
            exit()
        else:
            if AC[k] > 0:
                a = k
                for l in BC.keys():
                    if l != k:
                        b = l
                        break
            else:
                b = k
                for l in AC.keys():
                    if l != k:
                        a = l
                        break
            ans.append((a, b))
            S[a] -= 1
            S[b] -= 1
            AC[a] -= 1
            if not AC[a]:
                AC.pop(a)
            BC[b] -= 1
            if not BC[b]:
                BC.pop(b)

print('Yes')
ans.sort()
X = [b for a, b in ans]
print(*X)

Solution (Python):









def solve(N, A, B):
    buf = -1
    key = 0
    for i in range(N):
        if buf != A[i]:
            key = 0  
        if A[i] == B[i]:
            for j in range(key, N):
                if A[i] != A[j] and B[j] != A[i]:
                    B[i], B[j] = B[j], B[i]
                    key = j
                    break
            else:
                print('No')
                return
        buf = A[i]
    print('Yes')
    print(' '.join([str(i) for i in B]))


if __name__ == '__main__':
    
    N = int(input())
    
    A = [int(i) for i in input().split()]
    B = [int(i) for i in input().split()]
    
    solve(N, A, B)

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
cnt = [0 for i in range(n+1)]

def lb(x):
    l, r = 0, n
    while l < r:
        m = (l+r)//2
        if a[m] < x:
            l = m + 1
        else:
            r = m
    return l

def ub(x):
    l, r = 0, n
    while l < r:
        m = (l+r)//2
        if a[m] <= x:
            l = m + 1
        else:
            r = m
    return l

for i in range(n):
    l = lb(b[i])
    r = ub(b[i])-1
    if l > r:
        continue
    if l < i and i <= r:
        cnt[l+n-i]+=1
        cnt[0]+=1
        cnt[r-i+1]-=1
    elif i <= l:
        cnt[l-i]+=1
        cnt[r-i+1]-=1
    elif i > r:
        cnt[l+n-i]+=1
        cnt[r+n+1-i]-=1

res = 0
ans = -1
for i in range(n):
    res += cnt[i]
    if(res == 0):
        ans = i
if ans == -1:
    print("No")
else:
    print("Yes")
    for i in range(n):
        print(b[(i-ans+n)%n],end=' ')

Solution (Python):
from collections import defaultdict
def solve(N,A,B):
    d1=defaultdict(int)
    d2=defaultdict(int)
    for i in range(N):
        d1[A[i]]+=1
        d2[B[i]]+=1
    for i in d1:
        if d1[i]+d2[i]>N:
            return "No",[]
    else:
        return "Yes",B[::-1]
    
if __name__ == "__main__":
    N=int(input())
    A=[int(i) for i in input().split()][:N]
    B=[int(i) for i in input().split()][:N]
    a,b=solve(N,A,B)
    print(a)
    if b!=[]:
        
        k,z=0,N-1
        for i in range(N):
            if A[i]==b[i] and b[i]!=b[k]:
                b[i],b[k]=b[k],b[i]
                k+=1
            elif A[i]==b[i] and b[i]==b[k]:
                b[i],b[z]=b[z],b[i]
                z-=1
        z,k=0,N-1
        for i in range(N):
            if A[i]==b[i] and b[i]!=b[k]:
                b[i],b[k]=b[k],b[i]
                k-=1
            elif A[i]==b[i] and b[i]==b[k]:
                b[i],b[z]=b[z],b[i]
                z+=1
        print(*b)

Solution (Python):
from sys import exit

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

B = B[::-1]


need_swap = [i for i in range(n) if A[i] == B[i]]

if len(need_swap) == 0:
    print("Yes")
    print(" ".join(map(str,B)))
    exit()

val = A[need_swap[0]]
for i in range(n):
    if len(need_swap) == 0:
        break
    if A[i] != val and B[i] != val:
        j = need_swap.pop()
        B[i],B[j] = B[j],B[i]
if len(need_swap) == 0:
    print("Yes")
    print(" ".join(map(str,B)))
else:
    print("No")

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
b = b[::-1]

l = []
num = -1
for i in range(n):
    if a[i] == b[i]:
        l.append(i)
        num = a[i]

ind = 0
for i in range(n):
    if b[i] != num and a[i] != num and ind < len(l):
        b[i],b[l[ind]] = b[l[ind]],b[i]
        ind += 1
if ind < len(l):
    print("No")
else:
    print("Yes")
    print(*b)

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 9)

def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')







def solve():
    N = II()
    A = LI()
    B = sorted(LI(), reverse=True)
    tmp = []
    for i in range(N):
        if A[i] == B[i]:
            tmp.append((i, A[i]))

    j = 0
    while tmp:
        idx, x = tmp.pop()
        for i in range(j, N):
            b = B[i]
            j = i + 1
            if i == idx: continue
            if b != x and x != A[i]:
                B[i], B[idx] = B[idx], B[i]
                break
        else:
            print('No')
            return
    print('Yes')
    print(*B)


if __name__ == '__main__':
    solve()

Solution (Python):
import sys
import collections
import queue

input_methods=['clipboard','file','key']
using_method=1
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(tin())
mod=1000000007



def main():
	n = int(input())
	
	
	al = lin()
	bl = lin()
	al_c = collections.Counter(al)
	bl_c = collections.Counter(bl)
	ooo=queue.PriorityQueue()
	for k in al_c:
		if k not in bl_c:
			continue
			
		tt = al_c[k]+bl_c[k]
		if tt > n:
			print('No')
			return
		ooo.put((-tt, k))
		
	for k in bl_c:
		if k not in al_c:
			ooo.put((mod-k, k))
	
	print('Yes')
	ret = olt2(n,al,bl)
	print(*ret)
	return 
	
	ret = [-1] * n
	yobi = None
	_, cc = ooo.get()
	(_, yobi) = (_, None) if ooo.empty() else ooo.get()
	for i, v in enumerate(al):
		
		if bl_c[cc] == 0:
			cc = yobi
			nn, yobi = (_, None) if ooo.empty() else ooo.get()
			while yobi is not None and nn< 0 and yobi < v:
				ooo.put((mod - yobi, yobi))
				nn, yobi = (_, None) if ooo.empty() else ooo.get()
		
		if cc == v and yobi is None and ooo.empty():
			rr = olt2(n, al, bl)
			if rr is not None:
				print(*ret)
			return None
		
		if cc != v:
			ret[i] = cc
			bl_c[cc] -= 1
		else:
			ret[i] = yobi
			bl_c[yobi] -= 1
			if bl_c[yobi]==0:
				
				nn, yobi = (_, None) if ooo.empty() else ooo.get()
				while yobi is not None and nn < 0 and yobi < v:
					ooo.put((mod - yobi, yobi))
					nn, yobi = (_, None) if ooo.empty() else ooo.get()
			
	print(*ret)
			
			
def olt(n, al, bl):
	al_c = collections.Counter(al)
	bl_c = collections.Counter(bl)
	ooo=queue.PriorityQueue()
	for k in al_c:
		if k not in bl_c:
			continue
			
		tt = al_c[k]+bl_c[k]
		if tt > n:
			print('No')
			return
		ooo.put((-bl_c[k], k))
		
	for k in bl_c:
		if k not in al_c:
			ooo.put((mod-k, k))
	
	ret = [-1] * n
	yobi = None
	_, cc = ooo.get()
	(_, yobi) = (_, None) if ooo.empty() else ooo.get()
	for i, v in enumerate(al):
		
		if bl_c[cc] == 0:
			cc = yobi
			nn, yobi = (_, None) if ooo.empty() else ooo.get()
			while yobi is not None and nn< 0 and yobi < v:
				ooo.put((mod - yobi, yobi))
				nn, yobi = (_, None) if ooo.empty() else ooo.get()
		
		if cc == v and yobi is None and ooo.empty():
			ret = olt2(n, al, bl)
			print(*ret)
			return
		
		if cc != v:
			ret[i] = cc
			bl_c[cc] -= 1
		else:
			ret[i] = yobi
			bl_c[yobi] -= 1
			if bl_c[yobi]==0:
				
				nn, yobi = (_, None) if ooo.empty() else ooo.get()
				while yobi is not None and nn < 0 and yobi < v:
					ooo.put((mod - yobi, yobi))
					nn, yobi = (_, None) if ooo.empty() else ooo.get()
	print(*ret)
	return None
	

def olt2(n, al, bl):
	al_c = collections.Counter(al)
	bl_c = collections.Counter(bl)
	ooo=queue.PriorityQueue()
	for k in al_c:
		if k not in bl_c:
			continue
			
		tt = al_c[k]+bl_c[k]
		ooo.put((-tt, k))
		
	for k in bl_c:
		if k not in al_c:
			ooo.put((mod-k, k))
	
	ret = [-1] * n
	cv, cc = ooo.get()
	hold = None
	for i, v in enumerate(al):
		
		if cc == v and ooo.empty():
			return 1/0
		elif cc == v:
			ooo.put((mod+mod+cc, cc))
			cv, cc = ooo.get()
		
		while (cc < v and cv < 0) or cc == v:
			ooo.put((mod+cc+(0 if cc != v else mod), cc))
			pre = cv,cc
			cv, cc = ooo.get()
			if pre == (cv, cc):
				return 1/0
				
		ret[i]=cc
		bl_c[cc] -= 1
		if bl_c[cc] <= 0:
			cv, cc = (0,-1) if ooo.empty() else ooo.get()
			
	return ret
	



isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		
			
	ret = main()
	if ret is not None:
		print(ret)

Solution (Python):
N=int(input())
A=list(map(int, input().split()))
B=list(map(int, input().split()))
from collections import Counter as co
from collections import defaultdict
D,E=co(A),co(B)
for i in D:
  if D[i]+E[i]>N:
    print('No')
    exit()

d=defaultdict(int)
for i,e in enumerate(A):
  d[e]=i
ans=0
for i,e in enumerate(B):
  ans=max(ans,(d[e]-i+1))
s=B[-ans:]+B[:-ans]
print('Yes')
print(*s)

Solution (Python):
from collections import Counter
import numpy as np


def main():
    n = int(input())
    a = np.array([int(i) for i in input().split()])
    b = np.array([int(i) for i in input().split()])
    ca = Counter(a)
    cb = Counter(b)
    for k in cb.keys():
        if cb[k] > n - ca[k]:
            print("No")
            return
    shift = max(ca[k] for k in cb.keys())
    while any(a == b):
        b = np.roll(b, shift)
    print("Yes")
    print(*b)


if __name__ == '__main__':
    main()

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

cnt_b = Counter(bbb)
hq_both = []
free_a = []
idx_a = {}
cnt_a = {}
i = 0
for a, itr in groupby(aaa):
    cnt = len(list(itr))
    idx_a[a] = i
    cnt_a[a] = cnt
    if a in cnt_b:
        cnt_ab = cnt + cnt_b[a]
        if cnt_ab > n:
            print('No')
            exit()
        hq_both.append((-cnt_ab, a))
    else:
        free_a.append(a)
    i += cnt
heapify(hq_both)

ans = [-1] * n
remaining = n

while hq_both:
    cnt_ab, b = heappop(hq_both)
    cnt_ab = -cnt_ab
    assert cnt_ab == cnt_a[b] + cnt_b[b]
    assert cnt_ab <= remaining

    cb = cnt_b[b]
    while cb:
        if hq_both:
            _, a = heappop(hq_both)
        else:
            a = free_a.pop()
        ca = cnt_a[a]

        fill_len = min(ca, cb)
        i = idx_a[a]
        ans[i:i + fill_len] = [b] * fill_len
        remaining -= fill_len
        idx_a[a] += fill_len
        cnt_a[a] -= fill_len
        cnt_b[b] -= fill_len
        cb -= fill_len

        if cnt_a[a] > 0:
            if a in cnt_b and cnt_b[a] > 0:
                heappush(hq_both, (-(cnt_a[a] + cnt_b[a]), a))
            else:
                free_a.append(a)

    free_a.append(b)

for b, cb in cnt_b.items():
    if cb == 0:
        continue
    while cb:
        a = free_a.pop()
        ca = cnt_a[a]

        fill_len = min(ca, cb)
        i = idx_a[a]
        ans[i:i + fill_len] = [b] * fill_len
        idx_a[a] += fill_len
        cnt_a[a] -= fill_len
        cb -= fill_len

        if cnt_a[a] > 0:
            free_a.append(a)

print('Yes')
print(*ans)

Solution (Python):
from collections import Counter, defaultdict

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

ca = Counter(a)
cb = Counter(b)

for ka, va in ca.items():
    vb = cb[ka]
    if va + vb > n:
        print("No")
        exit()

print("Yes")
end = defaultdict(int)
for i, e in enumerate(a):
    end[e] = i

mx = 0
for i, e in enumerate(b):
    diff = end[e] - i + 1
    mx = max(mx, diff)

ans = b[-mx:] + b[:-mx]
print(*ans)

Solution (Python):
from sys import stdin
from random import randint
from time import time
input = lambda: stdin.readline().rstrip()
start = time()
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.reverse()
good = False
t = time() - start
while t < 1.8:
    ok = True
    for i in range(n):
        if a[i] == b[i]:
            rng = randint(0, n - 1)
            b[i], b[rng] = b[rng], b[i]
            ok = False
    if ok:
        good = True
        break
    t = time() - start
if good:
    print("Yes")
    print(*b)
else:
    print("No")

Solution (Python):
from sys import stdin
from random import randint
from time import time
input = lambda: stdin.readline().rstrip()
start = time()
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.reverse()
ok = 0
t = time() - start
while t < 1.8:
    cnt = 0
    for i in range(n):
        if a[i] == b[i]:
            rng = randint(0, n - 1)
            b[i], b[rng] = b[rng], b[i]
            cnt += 1
    if cnt == 0:
        ok = 1
        break
    t = time() - start
if ok == 1:
    print("Yes")
    print(*b)
else:
    print("No")

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

cntA = [0 for i in range(N+1)]
cntB = [0 for i in range(N+1)]

for i in range(N):
    cntA[A[i]] += 1
for i in range(N):
    cntB[B[i]] += 1

temp = False
for i in range(N):
    if cntA[A[i]] + cntB[A[i]] > N:
        temp = True
        break

if temp:
    print("No")


else:
    print("Yes")
    cA = 0
    cB = 0
    flag = False
    C = [B[N-i-1] for i in range(N)]
    D = [B[N-i-1] for i in range(N)]

    for i in range(1,N+1):
        if cA + cB + cntA[i] + cntB[i] == N:
            break
        elif cA + cB + cntA[i] + cntB[i] < N:
            cA += cntA[i]
            cB += cntB[i]
        elif cA + cB + cntA[i] >= N:
            if cA >= cntB[i]:
                for j in range(cntB[i]):
                    C[j] = i
                for j in range(N-cB-cntB[i]):
                    C[j+cntB[i]] = D[j]
            else:
                for j in range(cA):
                    C[j] = i
                for j in range(N-cB-cntB[i]):
                    C[j+cA] = D[j]
                for j in range(cB):
                    C[j+N-(cB+cntB[i]-cA)] = D[N-1-j]
                for j in range(cntB[i]-cA):
                    C[N-j-1] = i
            break
        else:
            if cntA[i] + cntB[i] <= N-cB:
                for j in range(cntB[i]-(N-cB-(cA+cntA[i]))):
                    C[j] = i
                for j in range(N-(cB+cntB[i])):
                    C[j+cntB[i]-(N-cB-(cA+cntA[i]))] = D[j]
                for j in range(N-cB-(cA+cntA[i])):
                    C[j+cA+cntA[i]] = i
            else:
                for j in range(cA):
                    C[j] = i
                for j in range(N-(cB+cntB[i])):
                    C[j+cA] = D[j]
                for j in range(cB):
                    C[j+N+cA-(cB+cntB[i])] = D[N-j-1]
                for j in range(cntB[i]-cA):
                    C[N-(cntB[i]-cA)+j] = i
            break
    F = [str(x) for x in C]
    print(" ".join(F))

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

cntA = [0 for i in range(N+1)]
cntB = [0 for i in range(N+1)]

for i in range(N):
    cntA[A[i]] += 1
for i in range(N):
    cntB[B[i]] += 1

temp = False
for i in range(N):
    if cntA[A[i]] + cntB[A[i]] > N:
        temp = True
        break

if temp:
    print("No")


else:
    print("Yes")
    cA = 0
    cB = 0
    flag = False
    C = [B[N-i-1] for i in range(N)]
    D = [B[N-i-1] for i in range(N)]

    for i in range(1,N+1):
        if cA + cB + cntA[i] + cntB[i] == N:
            break
        elif cA + cB + cntA[i] + cntB[i] < N:
            cA += cntA[i]
            cB += cntB[i]
        elif cA + cB + cntA[i] >= N:
            if cA >= cntB[i]:
                for j in range(cntB[i]):
                    C[j] = i
                for j in range(N-cB-cntB[i]):
                    C[j+cntB[i]] = D[j]
            else:
                for j in range(cA):
                    C[j] = i
                for j in range(N-cB-cntB[i]):
                    C[j+cA] = D[j]
                for j in range(cB):
                    C[j+N-(cB+cntB[i]-cA)] = D[N-1-j]
                for j in range(cntB[i]-cA):
                    C[N-j-1] = i
            break
        else:
            if cntA[i] + cntB[i] <= N-cB:
                for j in range(cntB[i]-(N-cB-(cA+cntA[i]))):
                    C[j] = i
                for j in range(N-(cB+cntB[i])):
                    C[j+cntB[i]-(N-cB-(cA+cntA[i]))] = D[j]
                for j in range(N-cB-(cA+cntA[i])):
                    C[j+cA+cntA[i]] = i
            else:
                for j in range(cA):
                    C[j] = i
                for j in range(N-(cB+cntB[i])):
                    C[j+cA] = D[j]
                for j in range(cB):
                    C[j+N+cA-(cB+cntB[i])] = D[N-j-1]
                for j in range(cntB[i]-cA):
                    C[N-(cntB[i]-cA)+j] = i
            break
    F = [str(x) for x in C]
    print(" ".join(F))

Solution (Python):
def get_ints():
      return list(map(int,input().split()))

n = int(input())
a = get_ints()
b = get_ints()

cnt = [0]*(n+1)
for x in a+b:
  cnt[x] += 1

q = [set() for i in range(n+1)]
for i in range(1,n+1):
  if cnt[i] > n:
    print('No')
    exit(0)
  q[cnt[i]].add(i)
print('Yes')

def make_cnt(a):
  cnt_ = {}
  for i in range(n):
    if a[i] not in cnt_:
      cnt_[a[i]] = [i]
    else:
      cnt_[a[i]].append(i)
  return cnt_

cnt_a = make_cnt(a)
cnt_b = make_cnt(b)

def get_any(cnt_, x):
  for key in cnt_.keys():
    if key != x:
      return key
  assert False

ans = [-1]*n

for i in range(n,0,-1):
  s = list(q[i])
  x,y = 0,0
  if len(s) == 0:
    x = get_any(cnt_a, -1)
    y = get_any(cnt_b, x)
  elif len(s) == 1:
    x = s[0]
    if x not in cnt_a:
      y = x
      x = get_any(cnt_a, y)
    else:
      y = get_any(cnt_b, x)
  else:
    x,y = s
    if x not in cnt_a:
      x,y = y,x

  ans[cnt_a[x][-1]] = y
  def update_cnt(cnt_, x):
    cnt_[x].pop()
    if len(cnt_[x]) == 0:
      del cnt_[x]
  def use(x):
    q[cnt[x]].remove(x)
    cnt[x] -= 1
    q[cnt[x]].add(x)
  update_cnt(cnt_a, x)
  update_cnt(cnt_b, y)
  use(x)
  use(y)

print(' '.join(map(str,ans)))

Solution (Python):
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
RB = B[::-1]

start = v = -1
seq = 0
for i,(a,b) in enumerate(zip(A,RB)):
    if a==b:
        v = a
        seq += 1
        if start == -1:
            start = i

if v == -1:
    print('Yes')
    print(*RB)
    exit()

if A.count(v) + B.count(v) > N:
    print('No')
    exit()

from bisect import bisect_left,bisect
al = bisect_left(A,v)
br = bisect(B,v)
rbl = N - br

m = min(seq,start,al,rbl)
RB[:m],RB[start:start+m] = RB[start:start+m],RB[:m]
seq -= m
start += m
if seq:
    RB[start:start+seq],RB[-seq:] = RB[-seq:],RB[start:start+seq]

assert all(a!=b for a,b in zip(A,RB))
print('Yes')
print(*RB)

Solution (Python):
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
RB = B[::-1]

start = v = -1
seq = 0
for i,(a,b) in enumerate(zip(A,RB)):
    if a==b:
        v = a
        seq += 1
        if start == -1:
            start = i

if v == -1:
    print('Yes')
    print(*RB)
    exit()

if A.count(v) + B.count(v) > N:
    print('No')
    exit()

from bisect import bisect_left,bisect
al = bisect_left(A,v)
bl = bisect_left(B,v)
br = bisect(B,v)
rbl = N - br

m = min(seq,start,al,rbl)
RB[:m],RB[start:start+m] = RB[start:start+m],RB[:m]
seq -= m
start += m
if seq:
    RB[start:start+seq],RB[-seq:] = RB[-seq:],RB[start:start+seq]

assert all(a!=b for a,b in zip(A,RB))
print('Yes')
print(*RB)

Solution (Python):



import sys
input = sys.stdin.readline


def make_cnt(a):
    cnt_ = {}
    for i in range(n):
        if a[i] not in cnt_:
            cnt_[a[i]] = [i]
        else:
            cnt_[a[i]].append(i)
    return cnt_


def get_any(cnt_, x):
    for key in cnt_.keys():
        if key != x:
            return key
    assert False


def update_cnt(cnt_, x):
    cnt_[x].pop()
    if len(cnt_[x]) == 0:
        del cnt_[x]


def use(x):
    q[cnt[x]].remove(x)
    cnt[x] -= 1
    q[cnt[x]].add(x)


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

cnt = [0] * (n + 1)
for x in a + b:
    cnt[x] += 1

q = [set() for i in range(n + 1)]
for i in range(1, n + 1):
    if cnt[i] > n:
        print("No")
        exit(0)
    q[cnt[i]].add(i)

print("Yes")

cnt_a = make_cnt(a)
cnt_b = make_cnt(b)

ans = [-1] * n



for i in range(n, 0, -1):
    s = list(q[i])
    x, y = 0, 0
    
    if len(s) == 0:
        x = get_any(cnt_a, -1)
        y = get_any(cnt_b, x)
    
    elif len(s) == 1:
        x = s[0]
        if x not in cnt_a:  
            y = x
            x = get_any(cnt_a, y)
        else:  
            y = get_any(cnt_b, x)
    
    else:
        x, y = s
        if x not in cnt_a:
            x, y = y, x

    ans[cnt_a[x][-1]] = y
    update_cnt(cnt_a, x)
    update_cnt(cnt_b, y)
    use(x)
    use(y)

print(*ans)