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 itertools import accumulate
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)

def solve():
    INF = 10**10

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

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

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

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

    imoss = list(accumulate(imoss))

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

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

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


solve()

Solution (Python):
def solve(A,B):
    i = 0
    j = 0


    C = defaultdict(list)
    D = [0]*len(B)
    flagA = -1
    flagB = -1
    while i<len(A) and j<len(B):
        if A[i][0] == B[j][0]:
            if i==len(A)-1:
                if j==len(B)-1:
                    break
                j+=1
                flagB = j-1
            else:
                i+=1
                flagA = i-1
        while len(C[A[i][0]]) < A[i][1] and D[j] < B[j][1]:
            C[A[i][0]].append(str(B[j][0]))
            D[j] += 1
        if D[j] == B[j][1]:
            if flagA>=0:
                i=flagA
                flagA = -1
            j+=1    
        else:
            if flagB>=0:
                j=flagB
                flagB = -1
            i+=1
        
        
        
    return C,D


from collections import Counter,defaultdict

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

A = Counter(A)
B = Counter(B)

A = [(c,A[c]) for c in A]
B = [(c,B[c]) for c in B]

A.sort(key = lambda x:x[1])
B.sort(key = lambda x:x[1])

i = 0
j = 0


C = defaultdict(list)
D = [0]*len(B)
flagA = -1
flagB = -1
while i<len(A) and j<len(B):
    if A[i][0] == B[j][0]:
        if i==len(A)-1:
            if j==len(B)-1:
                break
            j+=1
            flagB = j-1
        else:
            i+=1
            flagA = i-1
    while len(C[A[i][0]]) < A[i][1] and D[j] < B[j][1]:
        C[A[i][0]].append(str(B[j][0]))
        D[j] += 1
    if D[j] == B[j][1]:
        if flagA>=0:
            i=flagA
            flagA = -1
        j+=1    
    else:
        if flagB>=0:
            j=flagB
            flagB = -1
        i+=1
    
    
    

if sum(D)==N:
    print("Yes")
    E = [(c," ".join(C[c])) for c in C]
    
    E.sort(key = lambda x: x[0])
    E = [e[1] for e in E]
    print(*E)
else:
    A.sort(key = lambda x:x[1],reverse=True)
    B.sort(key = lambda x:x[1],reverse=True)

    i = 0
    j = 0


    C = defaultdict(list)
    D = [0]*len(B)
    flagA = -1
    flagB = -1
    while i<len(A) and j<len(B):
        if A[i][0] == B[j][0]:
            if i==len(A)-1:
                if j==len(B)-1:
                    break
                j+=1
                flagB = j-1
            else:
                i+=1
                flagA = i-1
        while len(C[A[i][0]]) < A[i][1] and D[j] < B[j][1]:
            C[A[i][0]].append(str(B[j][0]))
            D[j] += 1
        if D[j] == B[j][1]:
            if flagA>=0:
                i=flagA
                flagA = -1
            j+=1    
        else:
            if flagB>=0:
                j=flagB
                flagB = -1
            i+=1
        
        
        
    if sum(D)==N:
        print("Yes")
        E = [(c," ".join(C[c])) for c in C]
        
        E.sort(key = lambda x: x[0])
        E = [e[1] for e in E]
        print(*E)
    else:
        A.sort(key = lambda x:x[1],reverse=True)
        B.sort(key = lambda x:x[1],reverse=False)

        i = 0
        j = 0


        C = defaultdict(list)
        D = [0]*len(B)
        flagA = -1
        flagB = -1
        while i<len(A) and j<len(B):
            if A[i][0] == B[j][0]:
                if i==len(A)-1:
                    if j==len(B)-1:
                        break
                    j+=1
                    flagB = j-1
                else:
                    i+=1
                    flagA = i-1
            while len(C[A[i][0]]) < A[i][1] and D[j] < B[j][1]:
                C[A[i][0]].append(str(B[j][0]))
                D[j] += 1
            if D[j] == B[j][1]:
                if flagA>=0:
                    i=flagA
                    flagA = -1
                j+=1    
            else:
                if flagB>=0:
                    j=flagB
                    flagB = -1
                i+=1
            
            
            
        if sum(D)==N:
            print("Yes")
            E = [(c," ".join(C[c])) for c in C]
            
            E.sort(key = lambda x: x[0])
            E = [e[1] for e in E]
            print(*E)
        else:
            A.sort(key = lambda x:x[1],reverse=False)
            B.sort(key = lambda x:x[1],reverse=True)

            i = 0
            j = 0


            C = defaultdict(list)
            D = [0]*len(B)
            flagA = -1
            flagB = -1
            while i<len(A) and j<len(B):
                if A[i][0] == B[j][0]:
                    if i==len(A)-1:
                        if j==len(B)-1:
                            break
                        j+=1
                        flagB = j-1
                    else:
                        i+=1
                        flagA = i-1
                while len(C[A[i][0]]) < A[i][1] and D[j] < B[j][1]:
                    C[A[i][0]].append(str(B[j][0]))
                    D[j] += 1
                if D[j] == B[j][1]:
                    if flagA>=0:
                        i=flagA
                        flagA = -1
                    j+=1    
                else:
                    if flagB>=0:
                        j=flagB
                        flagB = -1
                    i+=1
                
                
                
            if sum(D)==N:
                print("Yes")
                E = [(c," ".join(C[c])) for c in C]
                
                E.sort(key = lambda x: x[0])
                E = [e[1] for e in E]
                print(*E)
            else:

                A.sort(key = lambda x:x[0],reverse=True)
                B.sort(key = lambda x:x[0],reverse=True)

                C,D = solve(A,B)
                if sum(D)==N:
                    print("Yes")
                    E = [(c," ".join(C[c])) for c in C]
                    
                    E.sort(key = lambda x: x[0])
                    E = [e[1] for e in E]
                    print(*E)
                else:
                    A.sort(key = lambda x:x[0],reverse=True)
                    B.sort(key = lambda x:x[0],reverse=False)

                    C,D = solve(A,B)
                    if sum(D)==N:
                        print("Yes")
                        E = [(c," ".join(C[c])) for c in C]
                        
                        E.sort(key = lambda x: x[0])
                        E = [e[1] for e in E]
                        print(*E)
                    else:
                        A.sort(key = lambda x:x[0],reverse=False)
                        B.sort(key = lambda x:x[0],reverse=True)
                        C,D = solve(A,B)
                        if sum(D)==N:
                            print("Yes")
                            E = [(c," ".join(C[c])) for c in C]
                            
                            E.sort(key = lambda x: x[0])
                            E = [e[1] for e in E]
                            print(*E)
                        else:

                            A.sort(key = lambda x:x[0],reverse=False)
                            B.sort(key = lambda x:x[0],reverse=False)
                            C,D = solve(A,B)
                            if sum(D)==N:
                                print("Yes")
                                E = [(c," ".join(C[c])) for c in C]
                                
                                E.sort(key = lambda x: x[0])
                                E = [e[1] for e in E]
                                print(*E)
                            else:
                                print("No")

Solution (Python):
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


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




h = []
from collections import Counter, defaultdict
from itertools import chain
ca = defaultdict(int)
ca.update(Counter(a))
cb = defaultdict(int)
cb.update(Counter(b))
ks = set(ca.keys()) | set(cb.keys())
ans = defaultdict(list)
done = 0
amari = 0
for k in ks:
    h.append((-ca[k], -cb[k], k))
h.sort(key=lambda x: x[0]+x[1])
la = []
lb = []
for va,vb,k in h:
    la.extend([k]*-va)
    lb.extend([k]*-vb)
na = [None]*n
nb = [None]*n
ia = 0
ib = n-1
ib2 = 0
for aa,bb,k in h:
    aa *= -1
    bb *= -1
    for _ in range(aa):
        na[ia] = k
        ia += 1
    for _ in range(bb):
        if na[ib]!=k:
            nb[ib] = k
            ib -= 1
        else:
            nb[ib2] = k
            ib2 += 1
if any((na[i]==nb[i]) for i in range(n)):
    print("No")
else:
    d = defaultdict(list)
    for i in range(n):
        d[na[i]].append(nb[i])
    ans = []
    for i in range(n):
        ans.append(d[a[i]].pop())
    print("Yes")
    write(" ".join(map(str, ans)))

Solution (Python):

max2 = lambda x,y: x if x > y else y
min2 = lambda x,y: x if x < y else y

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


def solve(A,B):
    N = len(A)
    start = [-1]*(N+1)
    end = [-1]*(N+1)
    start[A[0]] = 0
    end[A[-1]] = N

    for i,(p,a) in enumerate(zip(A,A[1:]),start=1):
        if a!=p:
            start[a] = i
            end[p] = i

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

    order = sorted((v for v in range(N+1) if ca[v] or cb[v]), key=lambda v:ca[v]+cb[v])
    res = [-1]*N
    
    
    
    try:
        remaining = [(v,cb[v]) for v in order]
        s = set(v for v,_ in remaining)
        for v in reversed(order):
            if v not in s:
                continue
            add_back = None
            i = start[v]
            j = end[v]
            while i < j:
                u,r = remaining.pop()
                if u == v:
                    add_back = (u,r)
                    u,r = remaining.pop()
                n = min2(r,j-i)
                for k in range(i,i+n):
                    res[k] = u
                i += n
                if n < r:
                    remaining.append((u,r-n))
                else:
                    s.discard(u)
            if add_back:
                remaining.append(add_back)

        i = 0
        for u,r in remaining:
            while r > 0:
                while res[i] >= 0:
                    i += 1
                res[i] = u
                r -= 1
                i += 1
    except IndexError:
        return None
    return res


if __name__ == '__main__':
    N = int(readline())
    A = list(map(int,readline().split()))
    B = list(map(int,readline().split()))
    res = solve(A,B)
    if res is None:
        print('No')
    else:
        print('Yes')
        print(*res)

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

A_cnt = Counter(A)
B_cnt = Counter(B)
for i in range(1,N+1):
    if N < A_cnt[i]+B_cnt[i]:
        print("No")
        break
else:
    print("Yes")
    cnt = 0
    indexes = {}
    alreadychecked = set()
    for i in range(N):
        if A[i] not in alreadychecked:
            indexes[A[i]] = i
            alreadychecked.add(A[i])
    zure = 0
    alreadychecked = set()
    for i in range(N-1,-1,-1):
        if B[i] not in alreadychecked:
            if B[i] in indexes and indexes[B[i]] <= i:
                zure = max(zure,i-indexes[B[i]]+1)
                alreadychecked.add(B[i])

    print(*B[zure:],*B[:zure])

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

d = defaultdict(list)
for i in range(N):
    a = A[i]
    b = B[i]
    if a==b:
        d[a].append(i)

h = []
for a in d:
    heapq.heappush(h,(-len(d[a]),a))

while len(h)>=2:
    x,a = heapq.heappop(h)
    y,b = heapq.heappop(h)
    i = d[a].pop()
    j = d[b].pop()
    B[i],B[j] = B[j],B[i]
    x += 1
    y += 1
    if x<0:
        heapq.heappush(h,(x,a))
    if y<0:
        heapq.heappush(h,(y,b))

if h:
    x,a = heapq.heappop(h)
    d[a] = d[a][::-1]
    for i in range(N):
        if len(d[a])==0:
            break
        if A[i] != a and B[i] != a:
            j = d[a].pop()
            B[i],B[j] = B[j],B[i]

ans = "Yes"
for i in range(N):
    if A[i]==B[i]:
        ans = "No"

print(ans)
if ans=="Yes":
    print(*B)

Solution (Python):
import sys
input = sys.stdin.readline
n = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))

from random import randint











C = [-1] * (n+2)
D = [-1] * (n+2)
for i in range(1, n):
    if A[i-1] != A[i]:
        C[A[i-1]] = i-1
C[A[-1]] = n-1

ind = 0
D[B[0]] = 0
for i in range(1, n):
    if B[i-1] != B[i]:
        D[B[i]] = i



sh = 0
for i in range(n+2):
    if C[i] != -1 and D[i] != -1:
        sh = max(sh, C[i]-D[i]+1)



N = [B[(i-sh)%n] for i in range(n)]
ng = 0

for i in range(n):
    if N[i] == A[i]:
        ng = 1
        break

if ng == 1:
    print("No")
else:
    print("Yes")
    print(*N)

Solution (Python):
n = int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
coa=[0]*(n+1)
cob=[0]*(n+1)
for i in a:
  coa[i]+=1
for i in b:
  cob[i]+=1
for i in range(n+1):
  if coa[i]+cob[i]>n:print("No");exit()
b.sort(reverse=True)
ans = b[:]
changed=0
for i in range(n):
  if a[i]==b[i]:
    ans[i],ans[changed]=ans[changed],ans[i]
    changed+=1
chenged_b=-1
for i in range(n):
  if a[i]==ans[i]:
    ans[i],ans[chenged_b]=ans[chenged_b],ans[i]
    chenged_b-=1
print("Yes")
print(*ans)

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

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

start = 0
ind = 0
NG = [0]*(2*N+1)

bdic = {}
for i, b in enumerate(B):
    if not b in bdic:
        bdic[b] = [i, i]
    else:
        bdic[b] = [min(bdic[b][0], i), max(bdic[b][1], i)]


for i, a in enumerate(A):
    if a in bdic:
        j1, j2 = bdic[a]
        if j1 >= i:
            NG[j1-i] += 1
            NG[j2-i+1] -= 1
        elif j2 < i:
            NG[j1-i+N] += 1
            NG[j2-i+1+N] -= 1
        else:
            NG[j1-i+N] += 1
            NG[0] += 1
            NG[j2-i+1] -= 1

start = -1
for i in range(N):
    if NG[i] == 0:
        start = i
        break
    NG[i+1] += NG[i]

if start == -1:
    print("No")
else:
    print("Yes")
    ans = []
    for i in range(N):
        ans.append(B[(i+start)%N])
    print(*ans)

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

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))



N = I()
A = LI()
B = LI()

if N == 1:
    if A[0] == B[0]:
        print('No')
    else:
        print('Yes')
        print(B[0])
    exit()

def place(i,j):
    if 0 <= j-i<= N-1:
        return j-i
    else:
        return N+j-i


C = set()
for i in range(N):
    C.add(i)

de = defaultdict(list)
for i in range(N):
    de[B[i]].append(i)

a = 0
b = 0
cu = [0]*(N+1)
for i in range(1,N):
    if A[i-1] == A[i]:
        b += 1
    else:
        b = i-1
        if len(de[A[a]]) == 0:
            a = i
            continue
        else:
            c = de[A[a]][0]
            d = de[A[a]][-1]
            if d-a >= 0:
                left = max(0,min(c-a,d-b))
                right = d-a
                cu[left] += 1
                cu[right+1] -= 1
            if c < b:
                left = N+c-b
                right = min(N-1,max(N+d-b,N+c-a))
                cu[left] += 1
                cu[right+1] -= 1
            a = i

if len(de[A[a]]) == 0:
    a = i
else:
    c = de[A[a]][0]
    d = de[A[a]][-1]
    if d-a >= 0:
        left = max(0,min(c-a,d-b))
        right = d-a
        cu[left] += 1
        cu[right+1] -= 1
    if c < b:
        left = N+c-b
        right = min(N-1,max(N+d-b,N+c-a))
        cu[left] += 1
        cu[right+1] -= 1
    a = i


cumu = [0]*N
for i in range(N):
    cumu[i] = cumu[i-1]+cu[i]

for k in range(N):
    if cumu[k] <= 0:
        print('Yes')
        ans1 = [B[i+k] for i in range(N-k)]
        ans2 = [B[i-(N-k)] for i in range(N-k,N)]
        ans1.extend(ans2)
        print(*ans1)
        exit()

print('No')

Solution (Python):
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
a = na()
b = na()

from collections import deque
d = deque(b)
i = 0
j = 0
ans = []

while d:
    k = d.popleft()
    if k == a[i]:
        d.append(k)
        j+=1
        if j > n:
            break
        continue
    ans.append(k)
    i+=1
else:
    print('Yes')
    print(*ans)
    exit()

d = deque(b)
i = 0
j = 0
ans = []

while d:
    k = d.pop()
    if k == a[i]:
        d.appendleft(k)
        j+=1
        if j > n:
            print('No')
            exit()
        continue
    ans.append(k)
    i+=1

print('Yes')
print(*ans)

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
    while any(a == b):
        s = max(ca[k] for k in cb.keys())
        b = np.roll(b, s)
    print("Yes")
    print(*b)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
A = [int(a)-1 for a in input().split()]
B = [int(a)-1 for a in input().split()]

LA = [0] * N + [N]
LB = [0] * N + [N]
j = 0
for i in range(N):
    LA[i] = j
    while j < N and A[j] == i:
        j += 1
j = 0
for i in range(N):
    LB[i] = j
    while j < N and B[j] == i:
        j += 1

NG = [0] * (N + 1)
for l1, r1, l2, r2 in zip(LA[:-1], LA[1:], LB[:-1], LB[1:]):
    ngl = l1-r2+1
    ngr = r1-l2
    if ngl < ngr < 0:
        NG[ngl+N] += 1
        NG[ngr+N] -= 1
    elif ngl < 0 <= ngr:
        NG[ngl+N] += 1
        NG[N] -= 1
        NG[0] += 1
        NG[ngr] -= 1
    elif 0 <= ngl < ngr:
        NG[ngl] += 1
        NG[ngr] -= 1
for i in range(N):
    NG[i+1] += NG[i]

for i in range(N):
    if NG[i]: continue
    print("Yes")
    print(*[a + 1 for a in (B[-i:] + B[:-i] if i else B)])
    break
else:
    print("No")

Solution (Python):
from collections import Counter
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = Counter(A)
D = Counter(B)
for k, v in C.items():
    if v + D[k] > n:
        print("No")
        exit()
print("Yes")
seen = set()
L = []
E = dict()
for i, a in enumerate(A):
    if a not in seen:
        seen.add(a)
        if i != 0:
            E[A[i-1]] = i-1
E[A[-1]] = -1
seen = [False]*n
K = [-1]*n
M = []
for k, v in D.items():
    if k in C:
        M.append((C[k]+v, k))
M.sort(reverse=True)
for p, q in M:
    if q in D:
        s = D[q]
        i = E[q]
        for j in range(s):
            if seen[(i+j+1)%n]:
                break
            seen[(i+j+1)%n] = True
            K[(i+j+1)%n] = q
            D[q] -= 1
        else:
            D.pop(q)
            
            
for i in range(n-1, -1, -1):
    if K[i] == -1:
        for k in D.keys():
            if A[i] != k:
                K[i] = k
                break
        D[k] -= 1
        if D[k] == 0:
            D.pop(k)
print(*K)

Solution (Python):
from collections import deque

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


cnt_a = [0 for i in range(N+1)]
cnt_b = [0 for i in range(N+1)]

for a in A:
    cnt_a[a]+=1
for b in B:
    cnt_b[b]+=1

for i in range(N+1):
    if cnt_a[i]+cnt_b[i]>N:
        exit(print("No"))

print("Yes")

aidx = [i for i in range(N)]
bidx = [N-i-1 for i in range(N)]
bidx_left = deque([])

res = [-1 for i in range(N)]

while aidx and bidx:
    if A[aidx[-1]]!=B[bidx[-1]]:
        res[bidx[-1]] = aidx[-1]
        bidx.pop()
        aidx.pop()
    elif bidx_left and B[bidx_left[0]]!=A[aidx[-1]]:
        res[bidx_left[0]] = aidx[-1]
        bidx_left.popleft()
        aidx.pop()
    else:
        bidx_left.append(bidx[-1])
        bidx.pop()

while aidx:
    if A[aidx[-1]]!=B[bidx_left[-1]]:
        res[bidx_left[-1]] = aidx[-1]
        bidx_left.pop()
        aidx.pop()
    else:
        break

aidx = aidx[::-1]
while aidx:
    if A[aidx[-1]]!=B[bidx_left[-1]]:
        res[bidx_left[-1]] = aidx[-1]
        bidx_left.pop()
        aidx.pop()
    else:
        break

if aidx:
    c = len(aidx)
    num = A[aidx[-1]]
    change = []
    for i in range(N):
        if not aidx:
            break
        if res[i]!=-1 and B[i]!=num and A[res[i]]!=num:
            res[bidx_left[-1]] = res[i]
            res[i] = aidx.pop()
            bidx_left.pop()

ans = [0 for i in range(N)]
for i in range(N):
    ans[res[i]]=B[i]

print(*ans)

Solution (Python):

from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for _ in range(n)]
def LIR(n):
    return [LI() for _ in range(n)]
def SR(n):
    return [S() for _ in range(n)]
def LSR(n):
    return [LS() for _ in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n = I()
    a = LI()
    b = LI()
    cnt = defaultdict(lambda : 0)
    for i in a:
        cnt[i] += 1
    for i in b:
        if not cnt[i]:
            continue
        cnt[i] += 1
    for i in cnt.values():
        if i > n:
            print("No")
            return
    r = n-1
    while 1:
        update = False
        for l in range(n):
            while r >= 0 and a[r] != b[r]:
                r -= 1
            if a[l] == b[l]:
                update = True
                b[l],b[r] = b[r],b[l]
                r -= 1
        if not update:
            break
    print("Yes")
    print(*b)
    return


if __name__ == "__main__":
    solve()

Solution (Python):

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

    ai, bi = 0, 0
    stride = 0
    while ai < n and bi < n:
        ax, bx = a[ai], b[bi]
        if ax == bx:
            cnt = 2

            ai += 1
            while ai < n and a[ai] == ax:
                cnt += 1
                ai += 1

            bi_copy = bi
            bi += 1
            while bi < n and b[bi] == bx:
                cnt += 1
                bi += 1

            if cnt > n:
                print('No')
                exit()

            if stride < ai - bi_copy:
                stride = ai - bi_copy

        elif ax < bx:
            ai += 1
        else:
            bi += 1

    print('Yes')
    print(' '.join(map(str, b[n-stride:] + b[:n-stride])))

main()

Solution (Python):

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

    ai, bi = 0, 0
    stride = 0
    while ai < n and bi < n:
        ax, bx = a[ai], b[bi]
        if ax == bx:
            cnt = 2

            ai += 1
            while ai < n and a[ai] == ax:
                cnt += 1
                ai += 1

            bi_copy = bi
            bi += 1
            while bi < n and b[bi] == bx:
                cnt += 1
                bi += 1

            if cnt > n:
                print('No')
                exit()

            if stride < ai - bi_copy:
                stride = ai - bi_copy

        elif ax < bx:
            ai += 1
        else:
            bi += 1

    print('Yes')
    print(' '.join(map(str, b[n-stride:] + b[:n-stride])))

main()

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

d = defaultdict(list)
for i in range(N):
    a = A[i]
    b = B[i]
    if a==b:
        d[a].append(i)

h = []
for a in d:
    heapq.heappush(h,(-len(d[a]),a))

while len(h)>=2:
    x,a = heapq.heappop(h)
    y,b = heapq.heappop(h)
    i = d[a].pop()
    j = d[b].pop()
    B[i],B[j] = B[j],B[i]
    x += 1
    y += 1
    if x<0:
        heapq.heappush(h,(x,a))
    if y<0:
        heapq.heappush(h,(y,b))

ans = "Yes"
if h:
    x,a = heapq.heappop(h)
    if len(d[a])*2>N:
        ans = "No"
    else:
        d[a] = d[a][::-1]
        for i in range(N):
            if len(d[a])==0:
                break
            if A[i] != a and B[i] != a:
                j = d[a].pop()
                B[i],B[j] = B[j],B[i]
if len(d[a])>0:
    ans = "No"                
print(ans)
if ans=="Yes":
    print(*B)

Solution (Python):
from collections import Counter

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


f = True
A_Counter = Counter(A)
B_Counter = Counter(B)
for a in A_Counter.keys():
    if N-A_Counter[a] < B_Counter[a]:
        f = False

if f:
    print('Yes')
    B.sort(reverse=True)
    n = 0
    sw = True
    for i in range(N):
        if A[i] == B[i]:
            if sw:
                B[i], B[n] = B[n], B[i]
                sw = False
            else:
                B[i], B[-1-n] = B[-1-n], B[i]
                n += 1
                sw = True
    print(*B)
else:
    print('No')

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

D = [[0, i] for i in range(N + 1)]


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

for d in D:
  if d[0] > N:
    print("No")
    exit()

print("Yes")

an = 0
am = 0
bn = 0
bm = 0
D = [1] * N
while an < N and bn < N:
  if A[an] == B[bn]:
    c = A[an]
  else:
    if A[an] > B[bn]:
      bn += 1
    else:
      an += 1
    continue
  am = an
  bm = bn
  while True:
    if am + 1 >= N:
      break
    if A[am + 1] == c:
      am += 1
    else:
      break
  while True:
    if bm + 1 >= N:
      break
    if B[bm + 1] == c:
      bm += 1
    else:
      break
  l = an - bm
  r = am - bn
  if l >= 0:
    for i in range(l, r + 1):
      D[i] = 0
  elif r >= 0:
    for i in range(l + N, N):
      D[i] = 0
    for i in range(r + 1):
      D[i] = 0
  else:
    for i in range(l + N, r + N):
      D[i] = 0
  an = am + 1
  bn = bm + 1

for i in range(N):
  if D[i] == 1:
    s = i
    break
else:
  print("No")
  exit()

Ans = [0] * N
for i in range(N):
  Ans[(i + s) % N] = B[i]

print(" ".join(list(map(str, Ans))))

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
b.reverse()
c = []
cs = -1
e = -1
for i in range(n):
  if a[i] > b[i]:
    c.append(1)
  elif a[i] == b[i]:
    c.append(0)
    e = a[i]
    if cs == -1:
      cs = i
  else:
    c.append(-1)



ans = 0
db = 0
for i in range(n):
  if a[i] == e:
    ans += 1
  if b[i] == e:
    ans += 1
  if a[i] == b[i]:
    db += 1
if ans > n:
  print('No')
  exit()
print('Yes')
cnt = 0


for i in range(n):
  if cnt == db:
    break
  
  if a[i] != e and b[i] != e:
    b[i],b[cs+cnt] = b[cs+cnt],b[i]
    cnt += 1
    
print(' '.join(map(str,b)))