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
INF = 1e12


def main():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    lA = Counter(A)
    lB = Counter(B)
    if max(Counter(A+B).values()) > N:
        print('No')
        exit()

    C = [0] * (N + 1)
    D = [0] * (N + 1)
    for i in range(N):
        C[i + 1] = lA[i + 1] + C[i]
        D[i + 1] = lB[i + 1] + D[i]
    shift = - INF
    for i in range(1, N + 1):
        shift = max(shift, C[i] - D[i - 1])
    print('Yes')
    ans = (B + B + B)[N-shift:2*N-shift]
    print(' '.join([str(a) for a in ans]))


if __name__ == "__main__":
    main()

Solution (Python):
from functools import reduce
from fractions import gcd
import math
import bisect
import itertools
import sys
input = sys.stdin.readline
INF = float("inf")



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


    C = [0] * (N+1)
    D = [0] * (N+1)
    for i in range(N):
        C[A[i]] += 1
        D[B[i]] += 1
    for i in range(N+1):
        if C[i] + D[i] > N:
            print("No")
            return
    for i in range(N):
        C[i+1] += C[i]
        D[i+1] += D[i]
    
    x = 0
    for i in range(1, N+1):
        if x < C[i] - D[i-1]:
            x = C[i] - D[i-1]
    

    print("Yes")
    for i in range(N):
        if i != 0:
            print(" ", end="")
        print(B[(i+N-x)%N], end="")
    print("")


if __name__ == '__main__':
    main()

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

for i in range(n):
  if cta[i]+ctb[i]>n:
    print('No')
    exit()

sa=[0]
sb=[0]
for i in range(n):
  sa.append(cta[i]+sa[-1])
  sb.append(ctb[i]+sb[-1])
l=[]
for i in range(n):
  l.append(sa[i+1]-sb[i])
ans=[]
maxl=max(l)
for i in range(n):
  ans.append(str(b[(i-maxl)%n]))
print('Yes')
print(' '.join(ans))

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

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

from collections import Counter

cA = Counter(A)
cB = Counter(B)





import heapq as hq
q = []
hq.heapify(q)
for key,value in cB.items():
  if key in cA:
    hq.heappush(q, (-(value + cA[key]), value, key))
    if value + cA[key] > N:
      print("No")
      exit(0)
  else:
    hq.heappush(q, (-value, value, key))
print("Yes")
a_ind = 0
ans = []

while a_ind < N:
  keep = []
  while True:
    allcnt, bcnt, key = hq.heappop(q)
    allcnt *= (-1)
    if A[a_ind] == key:
      keep.append((allcnt, bcnt, key))
    else:
      ans.append(key)
      if bcnt - 1 > 0:
        hq.heappush(q, (-(allcnt - 1), bcnt - 1, key))
      break
  for k in keep:
    hq.heappush(q, k)
  a_ind += 1
    
print(*ans)

Solution (Python):
from collections import*
from bisect import*
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
ca=Counter(a)
cb=Counter(b)
for i in a:
  if ca[i]+cb[i]>n:
    print('No')
    exit()
print('Yes')
ba=[bisect(a,i+1) for i in range(n)]
bb=[bisect_left(b,i+1) for i in range(n)]
i=0
for x,y in zip(ba,bb):
  i=max(i,x-y)
ans=b[n-i:]+b[:n-i]
print(*ans)

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from math import gcd
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, gcd
from operator import mul
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().rstrip().split()
def S(): return sys.stdin.readline().rstrip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]

mod=10**9+7

n=I()
A=LI()
B=sorted(LI(),reverse=True)
s=[]
c=0
ret=0
g,h=Counter(A+B).most_common()[0]
if h>n:
    print("No")
    exit()

for i in range(n):
    if A[i]==B[i]:
        ret+=2
        s+=[i]
        c=A[i]



for j in range(n):
    if A[j]!=c and B[j]!=c and s:
        k=s.pop()
        B[k],B[j]=B[j],B[k]

print("Yes")
print(*B)

Solution (Python):
def main():
    n=int(input())
    A=list(map(int,input().split()))
    B=list(map(int,input().split()))[::-1]
    Cnt=[0]*(n+1)
    for a,b in zip(A,B):
        Cnt[a]+=1
        Cnt[b]+=1
    if max(Cnt)>n:
        print('No')
        return
    l=0
    r=n-1
    for i in range(n):
        if A[i]==B[i]:
            if B[l]!=A[i] and A[l]!=A[i]:
                B[l],B[i]=B[i],B[l]
                l+=1
            else:
                B[r],B[i]=B[i],B[r]
                r-=1
    print('Yes')
    print(*B)
    return
    
if __name__=='__main__':
    main()

Solution (Python):
import sys
from collections import defaultdict
def input(): return sys.stdin.readline().strip()


def main():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    """
    2つのリストの関係を調べる云々は「二部グラフの完全マッチング問題」というカテゴリ名で呼ばれる。
    そしてこれに対しては「Hallの定理」というのが有効らしい。高校数学の美しい物語参照。

    特に大事なのがHall条件と呼ばれる方で、一見これはAの全ての部分集合を見ないといけないが
    部分集合のサイズが大きいと即座に|A| ¥subset |¥Gamma(A)|となるケースが多いよう？

    本問ではAが同一の元のみからなるケースのみ考えればよく（maspyさんブログ参照）、
    任意のx¥in Aに対して|{i|ai == x}| + |{i|bi == x}| <= Nが成り立てば答えはYesとなる。

    実際の二部グラフの構成方法は、|{i|ai == x}| + |{i|bi == x}|が大きいxから順にペアを作れば良い。

    ここで実装の注意点として、たくさん出てくる数から優先的に処理しないといけないが、
    ここにheapqを使うと２回ポップして出てきた数同士でペアを作る発想になるものの、
    一方からポップした数がBに存在しない等の場合何度もポップしてBにその数が含まれるかチェックすることになり
    非常に非効率になる。なのでheapqは使ってはいけない。

    なのでここでは
        hist[(出てきた回数)]=(その回数A+Bから出てくる数の集合)
    としてhistはリストで管理しないといけない。

    これむずすぎん？？？必要なデータ構造多すぎて訳わからんくなる。
    """
    num_kinds = defaultdict(int)
    hist = [set() for _ in range(N + 1)]
    for x in A + B: num_kinds[x] += 1
    for x, times in num_kinds.items():
        if times > N:
            print("No")
            return
        hist[times].add(x)
    print("Yes")

    num_to_idx_A = defaultdict(set)
    num_to_idx_B = defaultdict(set)
    num_to_cnt_A = defaultdict(int)
    num_to_cnt_B = defaultdict(int)
    for i, a in enumerate(A):
        num_to_idx_A[a].add(i)
        num_to_cnt_A[a] += 1
    for i, b in enumerate(B):
        num_to_idx_B[b].add(i)
        num_to_cnt_B[b] += 1


    B_new = [0] * N
    for times in range(N, 0, -1):
        nums = list(hist[times])
        l = len(nums)
        x, y = -1, -1
        if l == 2:
            x, y = nums
            for idxA in num_to_idx_A[x]: B_new[idxA] = y
            for idxA in num_to_idx_A[y]: B_new[idxA] = x
            break
        elif l == 1:
            x = nums[0]
            if num_to_idx_A[x]:
                y = -1
                for num in num_to_cnt_B:
                    if num != x:
                        y = num
                        break
            else:
                y = x
                x = -1
                for num in num_to_cnt_A:
                    if num != y:
                        x = num
                        break
        elif l == 0:
            x = -1
            for num in num_to_cnt_A:
                x = num
                break
            y = -1
            for num in num_to_cnt_B:
                if num != x:
                    y = num
                    break

        idxA = num_to_idx_A[x].pop()
        B_new[idxA] = y
        num_to_idx_B[y].pop()

        num_to_cnt_A[x] -= 1
        num_to_cnt_B[y] -= 1
        if num_to_cnt_A[x] == 0: del num_to_cnt_A[x]
        if num_to_cnt_B[y] == 0: del num_to_cnt_B[y]

        hist[num_kinds[x]].discard(x)
        hist[num_kinds[y]].discard(y)
        num_kinds[x] -= 1
        num_kinds[y] -= 1
        hist[num_kinds[x]].add(x)
        hist[num_kinds[y]].add(y)

    print(" ".join(map(str, B_new)))



if __name__ == "__main__":
    main()

Solution (Python):
import sys
from collections import defaultdict
def input(): return sys.stdin.readline().strip()


def main():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    """
    2つのリストの関係を調べる云々は「二部グラフの完全マッチング問題」というカテゴリ名で呼ばれる。
    そしてこれに対しては「Hallの定理」というのが有効らしい。高校数学の美しい物語参照。

    特に大事なのがHall条件と呼ばれる方で、一見これはAの全ての部分集合を見ないといけないが
    部分集合のサイズが大きいと即座に|A| ¥subset |¥Gamma(A)|となるケースが多いよう？

    本問ではAが同一の元のみからなるケースのみ考えればよく（maspyさんブログ参照）、
    任意のx¥in Aに対して|{i|ai == x}| + |{i|bi == x}| <= Nが成り立てば答えはYesとなる。

    実際の二部グラフの構成方法は、|{i|ai == x}| + |{i|bi == x}|が大きいxから順にペアを作れば良い。

    ここで実装の注意点として、たくさん出てくる数から優先的に処理しないといけないが、
    ここにheapqを使うと２回ポップして出てきた数同士でペアを作る発想になるものの、
    一方からポップした数がBに存在しない等の場合何度もポップしてBにその数が含まれるかチェックすることになり
    非常に非効率になる。なのでheapqは使ってはいけない。

    なのでここでは
        hist[(出てきた回数)]=(その回数A+Bから出てくる数の集合)
    としてhistはリストで管理しないといけない。

    これむずすぎん？？？必要なデータ構造多すぎて訳わからんくなる。
    """
    num_kinds = defaultdict(int)
    hist = [set() for _ in range(N + 1)]
    for x in A + B: num_kinds[x] += 1
    for x, times in num_kinds.items():
        if times > N:
            print("No")
            return
        hist[times].add(x)
    print("Yes")

    num_to_idx_A = defaultdict(set)
    num_to_idx_B = defaultdict(set)
    num_to_cnt_A = defaultdict(int)
    num_to_cnt_B = defaultdict(int)
    for i, a in enumerate(A):
        num_to_idx_A[a].add(i)
        num_to_cnt_A[a] += 1
    for i, b in enumerate(B):
        num_to_idx_B[b].add(i)
        num_to_cnt_B[b] += 1


    B_new = [0] * N
    for times in range(N, 0, -1):
        nums = list(hist[times])
        l = len(nums)
        x, y = -1, -1
        if l == 2:
            x, y = nums
            if not num_to_idx_A[x]: x, y = y, x
        elif l == 1:
            x = nums[0]
            if num_to_idx_A[x]:
                y = -1
                for num in num_to_cnt_B:
                    if num != x:
                        y = num
                        break
            else:
                y = x
                x = -1
                for num in num_to_cnt_A:
                    if num != y:
                        x = num
                        break
        elif l == 0:
            x = -1
            for num in num_to_cnt_A:
                x = num
                break
            y = -1
            for num in num_to_cnt_B:
                if num != x:
                    y = num
                    break

        idxA = num_to_idx_A[x].pop()
        B_new[idxA] = y
        num_to_idx_B[y].pop()

        num_to_cnt_A[x] -= 1
        num_to_cnt_B[y] -= 1
        if num_to_cnt_A[x] == 0: del num_to_cnt_A[x]
        if num_to_cnt_B[y] == 0: del num_to_cnt_B[y]

        hist[num_kinds[x]].discard(x)
        hist[num_kinds[y]].discard(y)
        num_kinds[x] -= 1
        num_kinds[y] -= 1
        hist[num_kinds[x]].add(x)
        hist[num_kinds[y]].add(y)

    print(" ".join(map(str, B_new)))



if __name__ == "__main__":
    main()

Solution (Python):
import sys
import heapq



def input():
    return sys.stdin.readline().rstrip()


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

    def diff(s,cc):
        count = 0
        for i in range(N):
            if A[i] == B[(i + s) % N]:
                count += 1
                if count>cc:
                    return cc+1
        if count == 0:
            print("Yes")
            L = []
            for i in range(N):
                L.append(B[(i + s) % N])
            print(*L)
            exit()

        return count
    n = N // 3
    l = 0
    r = N - 1
    diff(l,N)
    diff(r,N)

    while r - l > 2:
        m1 = l + (r - l) // 3
        m2 = l + 2 * (r - l) // 3
        a = diff(m1,N)
        b = diff(m2,a+1)
        if a > b:
            l = m1
        else:
            r = m2
    diff((l + r) // 2,N)

    print("No")


if __name__ == "__main__":
    main()

Solution (Python):
import sys
import heapq
from functools import lru_cache



def input():
    return sys.stdin.readline().rstrip()


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

    n = N // 3

    @lru_cache(maxsize=None)
    def diff(s):
        count = 0
        for i in range(N):
            if A[i] == B[(i + s) % N]:
                count += 1

        if count == 0:
            print("Yes")
            L = []
            for i in range(N):
                L.append(B[(i + s) %N])
            print(*L)
            exit()

        return count

    l = 0
    r = N - 1
    diff(l)
    diff(r)

    while r - l > 2:
        a = diff(l + (r - l) // 3)
        b = diff(l + 2 * (r - l) // 3)
        if a > b:
            l = l + (r - l) // 3
        else:
            r =l + 2 * (r - l) // 3
    diff((l+r)//2)

    print("No")


if __name__ == "__main__":
    main()

Solution (Python):
def solve():
    n = int(input())
    a = list(map(int,input().split()))
    b = list(map(int,input().split()))[::-1]
    cnt = [0]*(n+1)
    for x in a: cnt[x]+=1
    for x in b: cnt[x]+=1
    for x in cnt:
        if x  > n :
            print("No")
            return
    l = 0
    r = n-1;
    for i in range(n):
        if a[i] == b[i]:
            if b[l] != a[i] and a[l] != a[i]:
                b[l],b[i] = b[i],b[l]
                l+=1
            else:
                b[r],b[i] = b[i],b[r]
                r-=1
    print("Yes")
    print(" ".join(str(x) for x in b))

solve();

Solution (Python):
import bisect, collections, copy, heapq, itertools, math, string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int, sys.stdin.readline().rstrip().split())
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())

from collections import deque
from collections import Counter
import bisect
def main():
    N = I()
    A = LI()
    B = LI()
    A_cnt = Counter(A)
    B_cnt = Counter(B)
    for key in B_cnt.keys():
        x = A_cnt[key]
        if B_cnt[key] > N - x:
            print('No')
            exit()
    print('Yes')
    A_m = A_cnt.most_common()
    A_ = []
    for a_m in A_m:
        A_ += [a_m[0]] * a_m[1]
    B_m = deque(B_cnt.most_common())
    ANS = []
    for i in range(N):
        x = B_m[0][0]
        if A_[i] != x:
            ANS.append([A_[i], x])
            B_cnt[x] -= 1
            if B_cnt[x] == 0:
                B_m.popleft()
        elif A_[i] == x:
            if len(B_m) != 1:
                B_m.popleft()
                B_m.append((x, B_cnt[x]))
                y = B_m[0][0]
                ANS.append([x, y])
                B_cnt[y] -= 1
                if B_cnt[y] == 0:
                    B_m.popleft()
            else:
                for ans in ANS:
                    if ans[0] != x and ans[1] != x:
                        ANS.append([x, ans[1]])
                        ans[1] = x
                        break

    ANS.sort(key=lambda tup: tup[0])
    ANS_ = []
    for ans in ANS:
        ANS_.append(ans[1])
    print(' '.join(map(str, ANS_)))

if __name__ == "__main__":
    main()

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
b.reverse()
c=[0]*(n+1)
for i in a:
  c[i]+=1
for i in b:
  c[i]+=1
if n<max(c):
  print('No')
  exit(0)
l=0
while l<n and a[l]!=b[l]:
  l+=1
i=0
while l<n and a[l]==b[l]:
  while a[i]==b[l] or a[l]==b[i]:
    i+=1
  b[i],b[l]=b[l],b[i]
  l+=1
print('Yes')
print(' '.join([str(i) for i in b]))

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

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
cnt = [0]*(n+1)
for v in a:
    cnt[v] += 1
for v in b:
    cnt[v] += 1
f = True
for i in range(n+1):
    if cnt[i] > n:
        f = False
        break
if f:
    idx_a = [[] for _ in range(n+1)]
    idx_b = [[] for _ in range(n+1)]
    dic_a = {}
    dic_b = {}
    for i in range(n):
        idx_a[a[i]].append(i)
        idx_b[b[i]].append(i)
        if a[i] in dic_a:
            dic_a[a[i]] += 1
        else:
            dic_a[a[i]] = 1
        if b[i] in dic_b:
            dic_b[b[i]] += 1
        else:
            dic_b[b[i]] = 1
    ans = [None]*n
    rev_cnt = [set() for _ in range(n+1)]
    for i in range(n+1):
        if cnt[i] > 0:
            rev_cnt[cnt[i]].add(i)
    for i in reversed(range(1, n+1)):
        x, y = -1, -1
        if len(rev_cnt[i]) == 2:
            x, y = list(rev_cnt[i])
            if len(idx_a[x]) == 0:
                x, y = y, x
            rev_cnt[i-1] |= rev_cnt[i]
        elif len(rev_cnt[i]) == 1:
            x = list(rev_cnt[i])[0]
            if len(idx_a[x]) > 0:
                rm = None
                for v in dic_b.keys():
                    if dic_b[v] == 0:
                        rm = v
                        continue
                    if v != x:
                        y = v
                        break
                if rm is not None:
                    dic_b.pop(rm)
                s = dic_b[y]
                if y in dic_a:
                    s += dic_a[y]
                rev_cnt[s].remove(y)
                rev_cnt[s-1].add(y)
                rev_cnt[i-1].add(x)
            else:
                y = x
                rm = None
                for v in dic_a.keys():
                    if dic_a[v] == 0:
                        rm = v
                        continue
                    if v != y:
                        x = v
                        break
                if rm is not None:
                    dic_a.pop(rm)
                s = dic_a[x]
                if x in dic_b:
                    s += dic_b[x]
                rev_cnt[s].remove(x)
                rev_cnt[s-1].add(x)
                rev_cnt[i-1].add(y)
        else:
            rm = None
            for v in dic_a.keys():
                if dic_a[v] == 0:
                    rm = v
                    continue
                if v != y:
                    x = v
                    break
            if rm is not None:
                dic_a.pop(rm)
            s = dic_a[x]
            if x in dic_b:
                s += dic_b[x]
            rev_cnt[s].remove(x)
            rev_cnt[s-1].add(x)
            rm = None
            for v in dic_b.keys():
                if dic_b[v] == 0:
                    rm = v
                    continue
                if v != x:
                    y = v
                    break
            if rm is not None:
                dic_b.pop(rm)
            s = dic_b[y]
            if y in dic_a:
                s += dic_a[y]
            rev_cnt[s].remove(y)
            rev_cnt[s-1].add(y)
        ans[idx_a[x].pop(-1)] = y
        idx_b[y].pop(-1)
        dic_a[x] -= 1
        dic_b[y] -= 1
    print("Yes")
    for v in ans:
        print(v, end=" ")
else:
    print("No")

Solution (Python):
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from collections import Counter

    N = int(readline())
    a = list(map(int, readline().split()))
    b = list(map(int, readline().split()))

    cnt_a = Counter(a)
    cnt_b = Counter(b)

    acc_a = [0] * 200001
    acc_b = [0] * 200001

    for i in range(1, 200001):
        acc_a[i] = acc_a[i - 1] + cnt_a[i]
        acc_b[i] = acc_b[i - 1] + cnt_b[i]
        if cnt_a[i] + cnt_b[i] > N:
            return print("No")

    ans = 0
    for i in range(200000, 0, -1):
        score = acc_b[i] - acc_a[i - 1]
        ans = max(ans, score)

    print("Yes")

    res = b[ans:] + b[:ans]
    print(*res)

if __name__ == '__main__':
    main()

Solution (Python):
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from collections import Counter

    N = int(readline())
    a = list(map(int, readline().split()))
    b = list(map(int, readline().split()))

    cnt_a = Counter(a)
    cnt_b = Counter(b)

    acc_a = [0] * 200001
    acc_b = [0] * 200001

    for i in range(1, 200001):
        acc_a[i] = acc_a[i - 1] + cnt_a[i]
        acc_b[i] = acc_b[i - 1] + cnt_b[i]
        if cnt_a[i] + cnt_b[i] > N:
            return print("No")

    ans = 0
    for i in range(200000, 0, -1):
        score = acc_b[i] - acc_a[i - 1]
        ans = max(ans, score)

    print("Yes")

    res = b[ans:] + b[:ans]
    print(*res)

if __name__ == '__main__':
    main()

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

import collections
ac = collections.Counter(a)
bc = collections.Counter(b)

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

from collections import defaultdict
a_right  = defaultdict(int)
b_left = defaultdict(int)

for i in range(n):
    a_right[a[i]] = i

for i in reversed(range(n)):
    b_left[b[i]] = i

sft=[0]
for dup in set(a) & set(b):
    sft.append(a_right[dup] - b_left[dup]+1)

from collections import deque
b=deque(b)
b.rotate(max(sft))
print("Yes")
print(*b)

Solution (Python):
n=int(input())
a=[int(_) for _ in input().split()]
b=[int(_) for _ in input().split()]

d_a={}
d_b={}

for i in range(-1,n):
    d_a[i]=0
    d_b[i]=0

for i in range(n):
    d_a[a[i]-1]+=1
    d_b[b[i]-1]+=1

diff=0
c,d=0,0
for i in range(n):
    if d_a[i]+d_b[i]>n:
        print("No")
        exit()
    c+=d_a[i]
    d+=d_b[i-1]
    diff = max(diff,c-d)
print("Yes")



for i in range(n):
    print(b[(i-diff)%n],end=" ")
print()

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

inf=10e18
cc,cd=0,0
R=0
for i in range(n+1):
    if(A[i]+B[i]>n):
        R=inf
    else:
        cc+=A[i]
        R=max(R,cc-cd)
        cd+=B[i]
if(R==inf):
    print("No")
else:
    print("Yes")
    ans=" ".join(map(str,b[-R:]+b[:-R]))
    print(ans)

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

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

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

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

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

left = 0
right = n - 1

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

flag = 1

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

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

Solution (Python):
import collections

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

Atmp = 0
Btmp = 0

INF=10e18


C=collections.Counter(A)
D=collections.Counter(B)

currentC = 0
currentD = 0

rotation = 0



for n in range(N+1):

	if N < C[n] + D[n]:
		rotation = INF
		break

	currentC += C[n]
	rotation = max( rotation, currentC - currentD )
	currentD += D[n]

if rotation == INF:
	print("No")
else:
	print("Yes")
	
	print(" ".join(map(str,B[-rotation:] + B[:-rotation])))

Solution (Python):



def main():
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    b = list(reversed(b))
    bad = next((x for x, y in zip(a, b) if x == y), None)
    if bad is None:
        print('Yes')
        print(' '.join(map(str, b)))
    else:
        l_1 = sum(1 for x, y in zip(a, b) if x < bad < y)
        l_2 = sum(1 for x, y in zip(a, b) if x < y and bad in (x, y))
        l_3 = sum(1 for x, y in zip(a, b) if x == y)
        l_4 = sum(1 for x, y in zip(a, b) if x > y and bad in (x, y))
        l_5 = sum(1 for x, y in zip(a, b) if x > bad > y and x != bad)
        if l_3 > l_1 + l_5:
            print('No')
        else:
            good_part = b[:l_1] + b[l_1 + l_2 + l_3 + l_4:]
            bad_part = b[l_1 + l_2:l_1 + l_2 + l_3]
            b[l_1 + l_2:l_1 + l_2 + l_3] = good_part[:l_3]
            good_part[:l_3] = bad_part
            b[:l_1] = good_part[:l_1]
            b[l_1 + l_2 + l_3 + l_4:] = good_part[l_1:]
            assert all(x != y for x, y in zip(a, b))
            print('Yes')
            print(' '.join(map(str, b)))


if __name__ == '__main__':
    main()

Solution (Python):
import numpy as np
import sys 
read = sys.stdin.readline
n = int(input())
a = np.fromstring(read(), dtype=np.int32, sep=' ')
b = np.fromstring(read(), dtype=np.int32, sep=' ')[::-1]

kokan = []
same = -1
for i in range(n):
    if a[i] == b[i]:
        same = a[i]
if same == -1:
    print('Yes')
    print(*b)
    exit()

for i in range(n):
    if a[i] != b[i] and a[i] != same and b[i] != same:
        kokan.append(i)
for i in range(n):
    if a[i] == b[i]:
        if len(kokan) == 0:
            print('No')
            exit()
        else:
            j = kokan[-1]
            b[i], b[j] = b[j], b[i] 
            kokan.pop()
print('Yes')
print(*b)

Solution (Python):
from collections import defaultdict, deque

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

ns = defaultdict(int)
for i in a:
    ns[i] += 1
for i in b:
    ns[i] += 1
if max(ns.values()) > n:
    print('No')
    exit()

j = -1
k = -1
md = 0
for i in range(2, n + 1):
    while j + 1 < n and a[j + 1] < i:
        j += 1
    while k + 1 < n and b[k + 1] < i - 1:
        k += 1
    md = max(md, j - k)

for i in range(n):
    if a[i] == b[(i - md) % n]:
        md += 1
        break

d = deque(b)
d.rotate(md)

print('Yes')
print(' '.join([str(x) for x in d]))

Solution (Python):
from collections import defaultdict,deque
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True 
BIG = 10**18
R = 10**9 + 7


def ddprint(x):
  if DBG:
    print(x)

n = inn()
a = inl()
b = inl()
b.reverse()
left = n
same = -1
for i in range(n):
    if a[i]==b[i]:
        left = i
        same = a[i]
        break
if left==n:
    print('Yes')
    print(' '.join([str(x) for x in b]))
    exit()
for i in range(n):
    if same in [a[i],b[i]]:
        l2 = i
        break
right = r2 = -1
for i in range(n-1,-1,-1):
    if r2<0 and (same in [a[i], b[i]]):
        r2 = i+1
    if a[i]==b[i]:
        right = i+1
        break
if l2>=right-left:
    tmp = b[:right-left]
    b[:right-left] = b[left:right]
    b[left:right] = tmp
else:
    tmp = b[:l2]
    b[:l2] = b[left:left+l2]
    b[left:left+l2] = tmp
    if right+r2-left-l2>n:
        print('No')
        exit()
    tmp = b[r2:r2+right-l2-left]
    b[r2:r2+right-l2-left] = b[l2+left:right]
    b[l2+left:right] = tmp
print('Yes')
print(' '.join([str(x) for x in b]))

Solution (Python):
def main():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    cnt = [0] * (N + 1)
    for n in (A + B):
        cnt[n] += 1
    if max(cnt) > N:
        print('No')
        return
    
    B = B[::-1]
    dup, dup_indices = -1, list()
    for i in range(N):
        if A[i] == B[i]:
            dup = A[i]
            dup_indices.append(i)
    if dup == -1:
        
        print('Yes')
        print(' '.join(map(str, B)))
        return
    
    indices = list()
    for i in range(N):
        if A[i] != dup and B[i] != dup:
            indices.append(i)
    indices = indices[:len(dup_indices)]
    for i, j in zip(dup_indices, indices):
        B[i], B[j] = B[j], B[i]
    print('Yes')
    print(' '.join(map(str, B)))


if __name__ == '__main__':
    main()

Solution (Python):
N, *AB = map(int, open(0).read().split())
A, B = AB[:N], AB[N:]

C = [0] * (N + 1)
D = [0] * (N + 1)

for i, (a, b) in enumerate(zip(A, B)):
    C[a] += 1
    D[b] += 1

if any(c + d > N for c, d in zip(C, D)):
    print("No")
    quit()

for i in range(1, N + 1):
    C[i] += C[i - 1]
    D[i] += D[i - 1]

x = max(C[i] - D[i - 1] for i in range(1, N + 1))

print("Yes")
print(*[B[(i + N - x) % N] for i in range(N)])

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]

    idx_ng = []
    idx_ok = []

    for i in range(N):
        if A[i] == n and B[i] == n:
            idx_ng.append(i)
        elif A[i] != n and B[i] != n:
            idx_ok.append(i)

    for ng, ok in zip(idx_ng, idx_ok):
        B[ng], B[ok] = B[ok], B[ng]

    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]

    idx_ng = []
    idx_ok = []

    for i in range(N):
        if A[i] == n and B[i] == n:
            idx_ng.append(i)
        elif A[i] != n and B[i] != n:
            idx_ok.append(i)

    for ng, ok in zip(idx_ng, idx_ok):
        B[ng], B[ok] = B[ok], B[ng]

    print(*B)
    return


if __name__ == '__main__':
    main()