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):
from collections import Counter


def solve(n, a_list, b_list):
    count_a = Counter(a_list)
    count_b = Counter(b_list)
    count_ab = dict()
    for k in count_a.keys():
        if k in count_b.keys():
            if count_a[k] + count_b[k] > n:
                return ["No"]
            count_ab[k] = min(count_a[k], count_b[k])

    
    a_list_1 = []
    a_list_2 = []
    a = 0
    for i in range(n):
        if a != a_list[i]:
            if a_list[i] in count_ab.keys():
                c = count_ab[a_list[i]]
            else:
                c = 0
        a = a_list[i]
        if c > 0:
            a_list_1.append(a)
            c -= 1
        else:
            a_list_2.append(a)
    
    b_list_1 = []
    b_list_2 = []
    b = 0
    for i in range(n):
        if b != b_list[i]:
            if b_list[i] in count_ab.keys():
                c = count_ab[b_list[i]]
            else:
                c = 0
        b = b_list[i]
        if c > 0:
            b_list_1.append(b)
            c -= 1
        else:
            b_list_2.append(b)
    
    k_max = -1
    if len(count_ab.values()) == 0:
        return ["Yes", " ".join([str(b) for b in b_list])]
    d = max(count_ab.values())
    for k in count_ab.keys():
        if count_ab[k] == d:
            k_max = k
            break
    a_list_moved = a_list_1 + a_list_2
    b_list_moved = b_list_1[d:] + b_list_1[:d] + b_list_2

    
    if d * 2 > len(a_list_1):
        
        if count_a[k_max] >= count_b[k_max]:
            
            j = len(a_list_1)
            for i in range(len(a_list_1)):
                if a_list_moved[i] == b_list_moved[i] == k_max:
                    while a_list_moved[j] == k_max:
                        j += 1
                    a_list_moved[i], a_list_moved[j] = a_list_moved[j], a_list_moved[i]
        else:
            
            j = len(a_list_1)
            for i in range(len(a_list_1)):
                if a_list_moved[i] == b_list_moved[i] == k_max:
                    while b_list_moved[j] == k_max:
                        j += 1
                    b_list_moved[i], b_list_moved[j] = b_list_moved[j], b_list_moved[i]
    
    res_ab = list(sorted([(a, b) for a, b in zip(a_list_moved, b_list_moved)], key=lambda x: x[0]))
    res_b = " ".join([str(ab[1]) for ab in res_ab])
    
    return ["Yes", res_b]


def main():
    n = int(input())
    a_list = list(map(int, input().split()))
    b_list = list(map(int, input().split()))
    res = solve(n, a_list, b_list)
    for r in res:
        print(r)


def test():
    assert solve(6, [1, 1, 1, 2, 2, 3], [1, 1, 1, 2, 2, 3]) == ["Yes", "2 2 3 1 1 1"]
    assert solve(3, [1, 1, 2], [1, 1, 3]) == ["No"]
    assert solve(4, [1, 1, 2, 3], [1, 2, 3, 3]) == ["Yes", "2 3 3 1"]


if __name__ == "__main__":
    test()
    main()

Solution (Python):
import collections
import heapq

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

def construct():
    A_queue = [(-c, x) for x, c in collections.Counter(A).items()]
    heapq.heapify(A_queue)
    index = [None]*(N+1)
    for i, a in enumerate(A):
        if index[a] is None:
            index[a] = i

    B_queue = [(-c, x) for x, c in collections.Counter(B).items()]
    heapq.heapify(B_queue)

    answer = [None]*N

    while B_queue:
        neg_cb, b = heapq.heappop(B_queue)

        neg_ca, a = heapq.heappop(A_queue)
        if a == abs(b):
            if not A_queue: return None
            hold = (neg_ca, a)
            neg_ca, a = heapq.heappop(A_queue)
        else:
            hold = None

        answer[index[a]] = b
        index[a] += 1
        if neg_cb < -1:
            heapq.heappush(B_queue, (neg_cb+1, b))
        if neg_ca < -1:
            heapq.heappush(A_queue, (neg_ca+1, a))
        if hold is not None:
            heapq.heappush(A_queue, hold)
    else:
        return answer

answer = construct()
if answer is None:
    B = [-x for x in B]
    answer = construct()
    if answer is not None:
        answer = [-x for x in answer]

if answer:
    print('Yes')
    print(*answer)
else:
    print('No')

Solution (Python):
import sys
from bisect import bisect_right, bisect_left
from collections import Counter


def main():
    input = sys.stdin.buffer.readline
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    cnt = Counter(a + b)
    e, num = cnt.most_common(1)[0]
    if num > n:
        print("No")
    else:
        step = 0
        for e in set(a) & set(b):
            s = bisect_right(a, e) - bisect_left(b, e)
            step = max(step, s)
        ans = [0] * n
        for i in range(n):
            ans[i] = b[(i - step) % n]
        print("Yes")
        print(*ans)


if __name__ == "__main__":
    main()

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

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

def main():
    import heapq
    from collections import defaultdict
    dd = defaultdict(int)
    
    N=I()
    A=LI()
    B=LI()
    
    cntA=[0]*(N+1)
    cntB=[0]*(N+1)
    
    for i in range(N):
        cntA[A[i]]+=1
        cntB[B[i]]+=1
        
    cnt=[0]*(N+1)
    
    for i in range(N+1):
        v1=cntA[i]
        v2=cntB[i]
        if v1+v2>N:
            print("No")
            exit()
        cnt[i]=v1+v2
        
    hqa=[]
    heapq.heapify(hqa)
    hqb=[]
    heapq.heapify(hqb)
    
    for i in range(N+1):
        if cntA[i]!=0:
            a=(-1*cntA[i],i)
            
            heapq.heappush(hqa,a)
        if cntB[i]!=0:
            a=(-1*cntB[i],i)
            
            heapq.heappush(hqb,a)
            
    L=[]
    
    
    same=-1
    while hqa:
        ca,a=heapq.heappop(hqa)
        cb,b=heapq.heappop(hqb)
        
        
        
        if a!=b:
            use=max(ca,cb) * -1
            for _ in range(use):
                L.append((a,b))
                
            ca+=use
            if ca!=0:
                heapq.heappush(hqa,(ca,a))
            cb+=use
            if cb!=0:
                heapq.heappush(hqb,(cb,b))
                
        else:
            if not hqb:
                
                

                use=ca*(-1)
                cb+=use
                heapq.heappush(hqb,(cb,b))
                for _ in range(use):
                    L.append((a,a))
                same=a
                
            else:
                (cb2,b2)=heapq.heappop(hqb)
                heapq.heappush(hqb,(cb,b)) 
                
                
                use=max(ca,cb2) * -1
                
                for _ in range(use):
                    L.append((a,b2))
                    
                ca+=use
                if ca!=0:
                    heapq.heappush(hqa,(ca,a))
                cb2+=use
                if cb2!=0:
                    heapq.heappush(hqb,(cb2,b2))
                
    L.sort()
    ans=[0]*N
    
    samex=[]
    nots=[]
    
    for i in range(N):
        temp=L[i][1]
        ans[i]=temp
        
        if A[i]==same and ans[i]==same:
            samex.append(i)
            
    for i in range(N):
        if A[i]!=same and ans[i]!=same:
            nots.append(i)

            
    if same!=-1:
        
        
        
        
        for i in range(len(samex)):
            ans[samex[i]],ans[nots[i]] = ans[nots[i]], ans[samex[i]]
            
    now=0
    aaa=0
    for i in range(N):
        if ans[i]==A[i]:
            for j in range(N-1,-1,-1):
                aaa+=1
                if A[j]!=ans[i] and A[i]!=ans[j]:
                    ans[i],ans[j] = ans[j],ans[i]
                    now=j
                if aaa>=100000000:
                    print("No")
                    exit()

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


main()

Solution (Python):
import sys

sys.setrecursionlimit(10**6)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def lr(xx):
    ll=[-1]*(n+1)
    rr=[-1]*(n+1)
    for i,x in enumerate(xx):
        if ll[x]==-1:ll[x]=i
        if i==n-1 or x!=xx[i+1]:rr[x]=i+1
    return ll,rr

n=II()
aa=LI()
bb=LI()
all,arr=lr(aa)
bll,brr=lr(bb)

ca=[0]*(n+1)
cb=[0]*(n+1)
for a in aa:ca[a]+=1
for b in bb:cb[b]+=1
for i in range(n+1):
    if ca[i]+cb[i]>n:
        print("No")
        exit()
ng=[0]*(n+1)
for al,ar,bl,br in zip(all,arr,bll,brr):
    if al==-1 or bl==-1:continue
    if bl<ar:
        mn=max(0,al-br+1)
        mx=ar-bl
        ng[mn]+=1
        ng[mx]-=1
    else:
        mn=max(0,al+n-br+1)
        mx=min(n,ar+n-bl)
        ng[mn]+=1
        ng[mx]-=1

for i in range(n):ng[i+1]+=ng[i]
shift=-1
for i in range(n):
    if ng[i]==0:
        shift=i
        break
ans=bb[-shift:]+bb[:-shift]
print("Yes")
print(*ans)

Solution (Python):
from collections import Counter, deque
from random import randint

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

CA = Counter(A)
CB = Counter(B)
keys = set(A + B)
M = 0
for k in keys:
    M = max(M, CA[k] + CB[k])

if M > N:
    print('No')
    exit()

CB = CB.most_common()
L, R = [], []
for i, x in enumerate(CB):
    if i % 2 == 0:
        L.append(list(x))
    else:
        R.append(list(x))
X = deque(L + R[::-1])

y = L + R
ans = [None] * N
for i in range(N):
    if (X[0][0] != A[i]) and (X[-1][0] != A[i]):
        if X[0][1] > X[-1][1]:
            ans[i] = X[0][0]
            X[0][1] -= 1
            if X[0][1] == 0:
                X.popleft()
        else:
            ans[i] = X[-1][0]
            X[-1][1] -= 1
            if X[-1][1] == 0:
                X.pop()

    elif X[0][0] != A[i]:
        ans[i] = X[0][0]
        X[0][1] -= 1
        if X[0][1] == 0:
            X.popleft()
    else:
        ans[i] = X[-1][0]
        X[-1][1] -= 1
        if X[-1][1] == 0:
            X.pop()


for i in range(10):
    m = randint(0, N - 1)
    for i in range(N):
        if ans[i] != A[i]:
            continue
        ans[i], ans[m] = ans[m], ans[i]
        m += 1
        m %= N
print('Yes')
print(*ans, sep=' ')

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



from collections import deque, defaultdict, Counter












































































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):
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
Br = list(reversed(B))

NG = []
for i in range(N):
    if A[i]==Br[i]:
        NG.append(i)
        NGnumber = Br[i]
NGcnt = len(NG)

if NGcnt==0:
    print("Yes")
    print(*Br)
else:
    OK = []
    for i in range(N):
        if Br[i]!=NGnumber and A[i]!=NGnumber:
            OK.append(i)
    OKcnt = len(OK)

    if NGcnt>OKcnt:
        print("No")
    else:
        for i in range(NGcnt):
            Br[NG[i]],Br[OK[i]]=Br[OK[i]],Br[NG[i]]
        print("Yes")
        print(*Br)

Solution (Python):
import sys
import heapq
hpush = heapq.heappush
hpop = heapq.heappop
input = sys.stdin.readline
N = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ca = [0] * (N + 1)
cb = [0] * (N + 1)
for x in a: ca[x] += 1
for x in b: cb[x] += 1
for i in range(1, N + 1):
  if ca[i] + cb[i] > N:
    print("No")
    exit(0)

res = [0] * N
h = []
for i in range(1, N + 1):
  if cb[i]:
    r = N - ca[i] - cb[i] + 1
    hpush(h, (r, i))

s = []
table = [0] * (N + 1)
use = [0] * (N + 1)
for i in range(N):
  table[a[i]] += 1
  if len(s) and s[-1] != a[i]:
    x = s.pop()
    hpush(h, (N - ca[x] - cb[x] + 1 + table[x] + use[x], x))
  if len(h) == 0:
    print("No")
    exit(0)
  r, x = hpop(h)
  if x == a[i]:
    s.append(x)
    if len(h) == 0:
      print("No")
      exit(0)
    r, x = hpop(h)
  while r != N - ca[x] - cb[x] + 1 + table[x] + use[x]:
    hpush(h, (N - ca[x] - cb[x] + 1 + table[x] + use[x], x))
    r, x = hpop(h)
  res[i] = x
  use[x] += 1
  if cb[x] - use[x]: hpush(h, (r + 1, x))
  
for i in range(N):
  if res[i] == a[i]:
    print("No")
    break
else:
  print("Yes")
  print(*res)

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
b = b[::-1]
s = 0
e = 0
for i in range(n):
    if s == 0 and a[i] == b[i]:
        s = i+1
    if s > 0 and a[i] != b[i]:
        e = i+1
        break
if s == 0:
    print("Yes")
    print(*b)
    quit()
cl = a[s-1]
k = e-s
j = 0
for i in range(n):
    if s-1 <= i < e-1:
        continue
    if cl != b[i] and cl != a[i]:
        b[s-1+j] = b[i]
        b[i] = cl
        j += 1
    if j == k:
        break
for i in range(n):
    if a[i] == b[i]:
        print("No")
        quit()
print("Yes")
print(*b)

Solution (Python):


N = int(input())

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

CA = [0] * (N + 1)
CB = [0] * (N + 1)

for a in A:
  CA[a] += 1
for b in B:
  CB[b] += 1
X = 0
x = 0
y = 0
ans = [[0, 0] for i in range(N)]

for i in range(1, N + 1):
  if CA[i] + CB[i] > N:
    print('No')
    exit()
  if X + CA[i] + CB[i] < N:
    for j in range(X, X + CA[i]):
      ans[j][0] = i
    for j in range(X + CA[i], X + CA[i] + CB[i]):
      ans[j][1] = i
    X += CA[i] + CB[i]
    x += CA[i]
    y += CB[i]
    CA[i] = 0
    CB[i] = 0
  else:
    k = min(N, N + x - CB[i], X + CA[i])
    for j in range(X, k):
      ans[j][0] = i
    for j in range(k, N):
      ans[j][1] = i
    CA[i] -= k - X
    CB[i] -= N - k
    break
x = 1
y = 1
for j in range(N):
  while x < N + 1 and CA[x] == 0:
    x += 1
  if ans[j][0] == 0:
    ans[j][0] = x
    CA[x] -= 1
for j in range(N):
  while y < N + 1 and CB[y] == 0:
    y += 1
  if ans[j][1] == 0:
    ans[j][1] = y
    CB[y] -= 1
ans.sort()
print('Yes')
print(*(ans[i][1] for i in range(N)))

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

R = list(reversed(B))
flag = True
for i in range(N):
  if A[i] == R[i]:
    flag = False
    break
if flag:
  print('Yes')
  print(*R)
  exit()

l1 = B[N//2:]  + B[:N//2]
l2 = B[N//2+1:]  + B[:N//2+1]
flag1 = True
for i in range(N):
  if A[i] == l1[i]:
    flag1 = False
    break
flag2 = True
for i in range(N):
  if A[i] == l2[i]:
    flag2 = False
    break
if (flag1==False) and (flag2==False):
  print('No')
elif flag1 == True:
  print('Yes')
  print(*l1)
else:
  print('Yes')
  print(*l2)

Solution (Python):
from collections import Counter
import heapq

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

cur = n-1
bit = 1
for i in range(n):
    if a[i] == b[i]:
        while a[i]==b[cur] or a[cur]==b[i]:
            if cur == 0:
                bit = -1
            if bit == -1 and cur == n-1:
                print('No')
                exit(0)
            cur-=bit
        b[i], b[cur] = b[cur], b[i]
print('Yes')
print(' '.join(list(map(str, b))))

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

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


b.reverse()
mondai=-1
kasho=0
mondai_basho=-1
for i in range(n):
    if(a[i]==b[i]):
        mondai=a[i]
        kasho+=1
        if(kasho==1):
            mondai_basho=i



kano=True
ans=[]
if(kasho==0):
    ans=b
else:
    hajimea=0
    hajimeb=0
    owaria=0
    owarib=0
    for i in range(n):
        if(a[i]<mondai):
            hajimea+=1
        if(a[i]>mondai):
            owaria+=1
        if(b[i]>mondai):
            hajimeb+=1
        if(b[i]<mondai):
            owarib+=1
    hajime=min(hajimea,hajimeb)
    owari=min(owaria,owarib)
    if(kasho>hajime+owari):
        kano=False
    else:
        for i in range(kasho):
            if(i<hajime):
                temp=b[mondai_basho+i]
                b[mondai_basho+i]=b[i]
                b[i]=temp
            else:
                temp=b[mondai_basho+i]
                b[mondai_basho+i]=b[n-owari+i-hajime]
                b[n-owari+i-hajime]=temp
        ans=b

if(not kano):
    print("No")
else:
    print("Yes")
    for i in range(n):
        b[i]=str(b[i])
    print(" ".join(b))

Solution (Python):
from collections import Counter, deque

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

ca, cb = Counter(A), Counter(B)

cab = ca+cb

if any(c > N for c in cab.values()):
    print('No')
else:
    print('Yes')
    B.rotate(N//2)
    res = []
    while A:
        if A[0] != B[0]:
            A.popleft()
            res.append(str(B.popleft()))
        else:
            B.rotate()
        
    print(' '.join(res))

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

cnt = 0
step = 0

for i in range(N):
    if A[step] == B[i]:
        cnt += 1
    else:
        step += 1



flag = 0

for j in range(300):
    C = B[cnt+j:]+B[:cnt+j]
    flag = 0
    for i in range(N):
        if A[i] == C[i]:
            flag = 1
            break
    if i == N-1 and flag == 0:
        break
    
    
if flag == 1:
    print('No')
else:
    print('Yes')
    print(' '.join(map(str, C)))

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



from collections import deque, defaultdict, Counter












































































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):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))

cnt = [[0,i] for i in range(n+1)]
cnt_a = [0] * (n+1)
cnt_b = [0] * (n+1)

for ai,bi in zip(a,b):
    cnt[ai][0] += 1
    cnt[bi][0] += 1
    cnt_a[ai] += 1
    cnt_b[bi] += 1

cnt.sort(reverse=True)
new_al = []
new_ar = []
new_bl = []
new_br = []
done = 0
for _,i in cnt:
    if(done >= n):
        new_ar += [i] * cnt_a[i]
        new_bl += [i] * cnt_b[i]
    elif(done + cnt_a[i] + cnt_b[i] <= n):
        new_al += [i] * cnt_a[i]
        new_br += [i] * cnt_b[i]
    else:
        if(cnt_a[i] > n-done):
            new_al += [i] * (n-done)
            new_ar += [i] * (cnt_a[i] - n + done)
            new_bl += [i] * cnt_b[i]
        else:
            new_al += [i] * cnt_a[i]
            new_br += [i] * (n - done - cnt_a[i])
            new_bl += [i] * (cnt_b[i] - (n - done - cnt_a[i]))
    done += cnt_a[i] + cnt_b[i]


new_a = new_al + new_ar[::-1]
new_b = new_bl + new_br[::-1]
new = [[ai,bi] for ai,bi in zip(new_a,new_b)]


new.sort()

ans =[]
for ni in new:
    x,y = ni
    if(x==y):
        print('No')
        exit()
    ans.append(y)

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

Solution (Python):
import sys
from collections import defaultdict
import heapq

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

ABcnt = defaultdict(lambda: 0)
Acnt = defaultdict(lambda: 0)
Bcnt = defaultdict(lambda: 0)
for a, b in zip(A, B):
    ABcnt[a] += 1
    Acnt[a] += 1
    ABcnt[b] += 1
    Bcnt[b] += 1

for _, cnt in ABcnt.items():
    if cnt > N:
        print('No')
        sys.exit()

hq = [(-1 * cnt, k) for k, cnt in ABcnt.items()]
heapq.heapify(hq)
a2b = defaultdict(lambda: [])
arest = []
brest = []
while len(hq) > 1:
    cnt1, k1 = heapq.heappop(hq)
    cnt2, k2 = heapq.heappop(hq)
    if Acnt[k1] == 0:
        brest += [k1]*(-1 * cnt1)
        heapq.heappush(hq, (cnt2, k2))
        continue
    elif Bcnt[k1] == 0:
        arest += [k1]*(-1 * cnt1)
        heapq.heappush(hq, (cnt2, k2))
        continue
    elif Acnt[k2] == 0:
        brest += [k2]*(-1 * cnt2)
        heapq.heappush(hq, (cnt1, k1))
        continue
    elif Bcnt[k2] == 0:
        arest += [k2]*(-1 * cnt2)
        heapq.heappush(hq, (cnt1, k1))
        continue
    a2b[k1].append(k2)
    Acnt[k1] -= 1
    Bcnt[k2] -= 1
    if cnt1 < -1:
        heapq.heappush(hq, (cnt1 + 1, k1))
    if cnt2 < -1:
        heapq.heappush(hq, (cnt2 + 1, k2))
while len(hq) > 0:
    cnt, k = heapq.heappop(hq)
    if Acnt[k] == 0:
        brest += [k] * (-1 * cnt)
    elif Bcnt[k] == 0:
        arest += [k] * (-1 * cnt)
    else:
        a2b[k].append(brest.pop())
        Acnt[k] -= 1
        if cnt < -1:
            heapq.heappush(hq, (cnt+1, k))

ans = []
for a in A:
    if len(a2b[a]) != 0:
        ans.append(a2b[a].pop())
    else:
        ans.append(brest.pop())
print('Yes')
print(' '.join(map(str, ans)))

Solution (Python):
def solve(n):
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))[::-1]
    ind = [-1] * (n + 1)
    for i in range(n):
        if i == 0:
            ind[b[i]] = 0
        elif b[i] != b[i - 1]:
            ind[b[i]] = i
    cnt = 0
    for i in range(n):
        if a[i] != b[i]:
            continue
        else:
            swap = 0
            for j in range(b[i] - 1, 0, -1):
                if ind[j] != -1 or ind[j] >= ind[j - 1]:
                    swap = ind[j]
                    ind[j] += 1
                    break
            if n <= swap:
                swap = cnt
                cnt += 1
                cnt %= n
            b[i], b[swap] = b[swap], b[i]
    return a, b


def main():
    n = int(input())
    a, b = solve(n)
    if all(a[i] != b[i] for i in range(n)):
        print("Yes")
        print(" ".join(map(str, b)))
    else:
        print("No")


if __name__ == '__main__':
    main()

Solution (Python):
from collections import Counter
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

num = [0]*(n+1)
bc = [0]*(n+1)


for i in range(n):
    num[a[i]] += 1
    num[b[i]] += 1
    bc[b[i]] += 1

if max(num) > n:
    print("No")

else:
    nc = []
    for i in range(n):
        nc.append([num[i+1], i+1])
    nc.sort(reverse = True)

    usenum = []
    tot = 0
    q = []
    rem_num = []
    for i in range(n):
        x, y = nc[i]
        if tot >= n:
            rem_num.append((bc[y], y))
            continue
        tot += x
        usenum.append(y)
        q.extend([y]*bc[y])


    q.reverse()
    usenum = set(usenum)
    a_index = set()
    for i in range(n):
        if a[i] not in usenum:
            a_index.add(i)


    ans = [None]*(n)
    for ai in a_index:
        ans[ai] = q.pop()

    a_remain = set([i for i in range(n)]) - a_index
    a_remain = list(a_remain)
    a_remain.sort()
    from collections import deque
    a_remain = deque(a_remain)


    while q:
        now = q.pop()
        while True:
            ins = a_remain.popleft()
            if a[ins] == now:
                a_remain.append(ins)
                continue
            else:
                ans[ins] = now
                break

    q = []
    for x, y in rem_num:
        q.extend([y]*x)

    while q:
        now = q.pop()
        ins = a_remain.pop()
        ans[ins] = now

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

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
be = [-1] * n
la = [-1] * n
be2 = [-1] * n
la2 = [-1] * n
for i in range(n):
    if be[a[i] - 1] == -1:
        be[a[i] - 1] = i
    la[a[i] - 1] = i + 1
    if be2[b[i] - 1] == -1:
        be2[b[i] - 1] = i
    la2[b[i] - 1] = i + 1
l, r = 0, 2 * n
for i in range(n):
    if la[i] != -1 and la2[i] != -1:
        l = max(la[i] - be2[i], l)
        r = min(r, be[i] + n - la2[i])
if l > r:
    print('No')
else:
    print('Yes')
    print(*(b[n-l:] + b[:n-l]))

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

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

count = [0] * (n + 1)
counta = [0] * (n + 1)
countb = [0] * (n + 1)

for v in a:
    count[v] += 1
    counta[v] += 1
for v in b:
    count[v] += 1
    countb[v] += 1

for v in count:
    if v > n:
        print('No')
        exit()

outA = dict()
for v in a:
    outA[v] = []

import heapq
q = []
for v in range(n + 1):
    if count[v]:
        heapq.heappush(q,(-count[v],v))
    
while q[0][0] < 0:
    c, v = heapq.heappop(q)
    if count[v] + c:
        heapq.heappush(q,(-count[v],v))
        continue
    if counta[v]:
        for v2 in sb:
            if v2 != v:
                break
        else:
            print('No')
            exit()
        outA[v].append(v2)
        count[v] -= 1
        count[v2] -= 1
        counta[v] -= 1
        countb[v2] -= 1
        if counta[v] == 0:
            sa.remove(v)
        if countb[v2] == 0:
            sb.remove(v2)
    else:
        for v2 in sa:
            if v2 != v:
                break
        else:
            print('No')
            exit()
        outA[v2].append(v)
        count[v] -= 1
        count[v2] -= 1
        counta[v2] -= 1
        countb[v] -= 1
        if counta[v2] == 0:
            sa.remove(v2)
        if countb[v] == 0:
            sb.remove(v)
    if count[v]:
        heapq.heappush(q, (-count[v], v))

out = []
for v in a:
    out.append(outA[v].pop())
print('Yes')
print(' '.join(map(str,out)))

Solution (Python):

import sys, bisect, math, itertools, heapq, collections
from operator import itemgetter

from functools import lru_cache
import copy


input = sys.stdin.readline
INF = float('inf')
mod = 10**9 + 7
eps = 10**-7




def inp():
    '''
    一つの整数
    '''
    return int(input())


def inpl():
    '''
    一行に複数の整数
    '''
    return list(map(int, input().split()))


def str_inp():
    '''
    文字列をリストとして読み込む
    '''
    return list(input()[:-1])




n = inp()
a = inpl()
b = inpl()
a_digest = collections.defaultdict(int)
b_digest = collections.defaultdict(int)
for i in range(n):
    a_digest[a[i]] += 1
    b_digest[b[i]] += 1
for i in range(1, n + 1):
    if a_digest[i] > n - b_digest[i]:
        print("No")
        exit()
print("Yes")
b.sort(reverse=True)
ptr = 0
for i in range(n):
    if a[i] == b[i]:
        while a[i] == b[ptr] or a[ptr] == b[i]:
            ptr += 1
            if ptr == n:
                ptr = 0
        b[ptr], b[i] = b[i], b[ptr]
print(*b)

Solution (Python):
N=int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
B.sort(reverse=True)
Arev=sorted(A, reverse=True)
Brev=sorted(B)
atai=0
s=0
for i in range(len(A)):
    if A[i]==B[i]:
        atai=A[i]
        s+=1
C=[]
for i in range(len(A)):
    C.append(A[i]-B[i])
if s>0:
    hajime=C.index(0)
if s==0:
    print("Yes")
    print(*B)
else:
    Acount=A.count(atai)
    Bcount=B.count(atai)
    if N-Acount<Bcount:
        print("No")
    else:
        afirst=A.index(atai)
        alast=N-1-Arev.index(atai)
        bfirst=B.index(atai)
        blast=N-1-Brev.index(atai)
        t=min(afirst,bfirst)
        if t>=s:
            for i in range(0,s):
                B[hajime+i]=B[i]
                B[i]=atai
        else:
            for i in range(0,t):
                B[hajime+i]=B[i]
                B[i]=atai
            ss=s-t
            for i in range(0,ss):
                B[hajime+t+i]=B[-i-1]
                B[-i-1]=atai
        print("Yes")
        print(*B)

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

N=int(input())
A=tuple(map(int,input().split()))
B=tuple(map(int,input().split()))
sum = [0]*N

for i in range(N):
    sum[A[i]-1] += 1
    sum[B[i]-1] += 1

if max(sum) > N:
    print('No')
    exit()

print('Yes')
for i in range(N):
    hit = False
    for j in range(N):
        a = A[j]
        b = B[(j + i) % N]
        if a == b:
            hit = True
            break
    if not hit:
        ans = []
        for j in range(N):
            ans.append(str(B[(j+i) % N]))
        print(" ".join(ans))
        exit()

Solution (Python):
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)

f = 0

for num, val in cA.items():
    if num not in cB:
        continue
    else:
        if cB[num] + val > N:
            f = 1

tpA = [-1] * (N + 1)
tpB = [-1] * (N + 1)
a = A[0]
b = B[0]
tpB[b] = 0
for i in range(1, N):
    if a != A[i]:
        tpA[a] = i
        a = A[i]
    if b != B[i]:
        b = B[i]
        tpB[b] = i
tpA[a] = N


ans = [0] * N
if f == 1:
    print("No")
else:
    print("Yes")
    t = 0
    for i in range(N+1):
        if tpA[i] >= 0 and tpB[i] >= 0:
            t = max(t, tpA[i] - tpB[i])
    for i in range(N):
        ans[i+t-N] = B[i]
    
    print(" ".join([str(_) for _ in ans]))

Solution (Python):
n=int(input())
y=lambda:[*map(int,input().split())]
a,b=y(),y()[::-1]
c=0
for i in range(n):
  if a[i]==b[i]:c=a[i]
if c<1:print("Yes");print(' '.join(map(str,b)));quit()
al,bl,ah,bh=[-1]*4
ea=eb=0
for i in range(n):
  if al<0 and a[i]==c:al=i
  if bl<0 and b[i]==c:bl=i
  if al<0:ea+=1
  if bl<0:eb+=1
  if ah<0 and al>=0 and a[i]!=c:ah=i
  if bh<0 and bl>=0 and b[i]!=c:bh=i
if ah<0:ah=n
if bh<0:bh=n
t=ah+bh-al-bl
if ah+bh-al-bl>n:print("No");quit()
o1=min(bh-bl,ea,ea-eb+ah-al)
print("Yes")
print(' '.join(map(str,[c]*o1+b[:eb]+b[eb+bh-bl:]+[c]*(bh-bl-o1))))

Solution (Python):

import sys
input = sys.stdin.readline
import random

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











b.reverse()

same_val = None
same_id = []
for i, (ai, bi) in enumerate(zip(a, b)):
    if ai == bi:
        same_val = ai
        same_id.append(i)

changeable = []
for i, (ai, bi) in enumerate(zip(a, b)):
    if b[i] != same_val and a[i] != same_val:
        changeable.append(i)

if len(same_id) > len(changeable):
    print("No")
    exit()
for s, c in zip(same_id, changeable):
    b[s], b[c] = b[c], b[s]

print("Yes")
print(*b)