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



"""






















using namespace std;

using int64 = long long;




template <class T>
inline void eraque(std::vector<T>& vec) {
  vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
  return;
}

template <class T>
inline int lower_position(const std::vector<T>& vec, T val) {
  return static_cast<int>(std::distance(
      vec.begin(), std::lower_bound(vec.begin(), vec.end(), val)));
}

template <class T>
inline int upper_position(const std::vector<T>& vec, T val) {
  return static_cast<int>(std::distance(
      vec.begin(), std::upper_bound(vec.begin(), vec.end(), val)));
}

template <class T>
inline std::string to_binary(T n) {
  assert(n > 0);
  std::string ret = "";
  while (n) ret += (n & 1) ? '1' : '0', n >>= 1;
  std::reverse(ret.begin(), ret.end());
  return ret;
}

template <class T>
inline void println(T val) {
  std::cout << val << '\n';
}

template <class T>
inline void println(const std::vector<T>& vec) {
  int sz = vec.size();
  for (int i = 0; i < sz; ++i) std::cout << vec[i] << " \n"[i == sz - 1];
}

inline void Yes(bool cond) {
  println(cond ? "Yes" : "No");
}

inline void YES(bool cond) {
  println(cond ? "YES" : "NO");
}

template <class T>
using binary_heap = std::priority_queue<T, std::vector<T>, std::greater<T>>;

template <class T>
std::istream& operator>>(std::istream& is, std::vector<T>& vec) {
  for (T& e : vec) is >> e;
  return is;
}

template <class T, class U>
std::istream& operator>>(std::istream& is, std::pair<T, U>& p) {
  return is >> p.first >> p.second;
}

template <class Tuple, std::size_t... Is>
void tuple_in(std::istream& is, Tuple& tp, std::index_sequence<Is...>) {
  ((is >> std::get<Is>(tp)), ...);
}

template <class... Args>
std::istream& operator>>(std::istream& is, std::tuple<Args...>& tp) {
  tuple_in(is, tp, std::index_sequence_for<Args...>{});
  return is;
}

class Timer {
 public:
  // (second)
  double get_elapsed_time() {
    return static_cast<double>(get_cycle() - start_) /
           static_cast<double>(clock_frequency_);
  }

  void start() { start_ = get_cycle(); }

 private:
  int64_t start_;
  //static constexpr int64_t clock_frequency_ = 1800000000; // Local
  static constexpr int64_t clock_frequency_ = 3000000000; // AtCoder
  //static constexpr int64_t clock_frequency_ = 3600000000; // Codeforces
  //static constexpr int64_t clock_frequency_ = 2300000000; // yukicoder

  int64_t get_cycle() {
    uint32_t low, high;
    __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
    return (static_cast<int64_t>(low)) | (static_cast<int64_t>(high) << 32);
  }
};

// This is xoroshiro128+ 1.0
// Reference : http://prng.di.unimi.it/xoroshiro128plus.c
class Xoroshiro {
 public:
  Xoroshiro() {
    s[0] = static_cast<uint64_t>(std::chrono::steady_clock::now().time_since_epoch().count());
    s[1] = s[0] ^ 0xffffffffful;
    for (int i = 0; i < (1 << 6); ++i) next();
  }

  using result_type = uint64_t;
  static constexpr uint64_t min() { return std::numeric_limits<result_type>::min(); }
  static constexpr uint64_t max() { return std::numeric_limits<result_type>::max(); }

  uint64_t operator()() { return next(); }

 private:
  uint64_t s[2];

  static inline uint64_t rotl(const uint64_t x, int k) {
    return (x << k) | (x >> (64 - k));
  }

  uint64_t next() {
    const uint64_t s0 = s[0];
    uint64_t s1 = s[1];
    const uint64_t result = s0 + s1;
    s1 ^= s0;
    s[0] = rotl(s0, 24) ^ s1 ^ (s1 << 16);
    s[1] = rotl(s1, 37);

    return result;
  }
};


int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);

  Timer time;
  time.start();

  Xoroshiro rng;

  int n; cin >> n;
  vector<int> a(n), b(n); cin >> a >> b;

  vector<int> cnt_a(202020, 0), cnt_b(202020);
  for (int e : a) ++cnt_a[e];
  for (int e : b) ++cnt_b[e];
  for (int i = 0; i < 202020; ++i) {
    if (cnt_a[i] + cnt_b[i] > n) {
      Yes(0); return 0;
    }
  }

  Yes(1);

  uniform_int_distribution<int> dist(0, n - 1);

  // B を reverse してから、a[i] = b[i] になってるところを見つけたらランダムに
  // swap して解消する。これを時間いっぱいやる
  // これで通ったけど、いいのか？！

  reverse(all(b));

  while (true) {
    for (int i = 0; i < n; ++i) {
      if (time.get_elapsed_time() > 1.9) {
        println(b); return 0;
      }
      if (a[i] == b[i]) {
        int cur = a[i];
        int p = i;
        while (b[p] == cur) {
          p = dist(rng);
          if (time.get_elapsed_time() > 1.9) {
            println(b); return 0;
          }
        }
        swap(b[i], b[p]);
        if (time.get_elapsed_time() > 1.9) {
          println(b); return 0;
        }
      }
    }
  }

  return 0;
}

"""

import base64
import subprocess
import zlib


exe_bin = "c%1E9eRLaDc7OVCEayW~f)gB4h)9*37>KaqeAs{&%eImykP{O-Z1_kfvLwf9WXUUyVw+M3E5b6zDC^yF*qm<J<s8o0hW1d{)0P4)

open("./kyomu", 'wb').write(zlib.decompress(base64.b85decode(exe_bin)))
subprocess.run(["chmod +x ./kyomu"], shell=True)
subprocess.run(["./kyomu"], shell=True)

Solution (Python):
import math
import numpy as np
import decimal
import collections
import itertools
import sys
import random

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.par = [-1 for i in range(self.n)]
    def find(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]
    def unite(self, x, y):
        p = self.find(x)
        q = self.find(y)
        if p == q:
            return None
        if p > q:
            p, q = q, p
        self.par[p] += self.par[q]
        self.par[q] = p
    def same(self, x, y):
        return self.find(x) == self.find(y)
    def size(self, x):
        return -self.par[self.find(x)]


def prime_numbers(x):
    if x < 2:
        return []
    prime_numbers = [i for i in range(x)]
    prime_numbers[1] = 0
    for prime_number in prime_numbers:
        if prime_number > math.sqrt(x):
            break
        if prime_number == 0:
            continue
        for composite_number in range(2 * prime_number, x, prime_number):
            prime_numbers[composite_number] = 0
    return [prime_number for prime_number in prime_numbers if prime_number != 0]
def is_prime(x):
    if x < 2:
        return False
    if x == 2 or x == 3 or x == 5:
        return True
    if x % 2 == 0 or x % 3 == 0 or x % 5 == 0:
        return False
    prime_number = 7
    difference = 4
    while prime_number <= math.sqrt(x):
        if x % prime_number == 0:
            return False
        prime_number += difference
        difference = 6 - difference
    return True

def prime_factorize(n):
    res = []
    while n % 2 == 0:
        res.append(2)
        n //= 2
    f = 3
    while f ** 2 <= n:
        if n % f == 0:
            res.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        res.append(n)
    return res

mod = 10 ** 9 + 7
class nCr():
    def __init__(self, n):
        self.n = n
        self.fa = [1] * (self.n + 1)
        self.fi = [1] * (self.n + 1)
        for i in range(1, self.n + 1):
            self.fa[i] = self.fa[i - 1] * i % mod
            self.fi[i] = pow(self.fa[i], mod - 2, mod)
    def comb(self, n, r):
        if n < r:return 0
        if n < 0 or r < 0:return 0
        return self.fa[n] * self.fi[r] % mod * self.fi[n - r] % mod

def extgcd(a, b, d = 0):
    g = a
    if b == 0:
        x, y = 1, 0
    else:
        x, y, g = extgcd(b, a % b)
        x, y = y, x - a // b * y
    return x, y, g

class BinaryIndexedTree():
    def __init__(self, n):
        self.n = n
        self.BIT = [0] * (self.n + 1)
    def add(self, i, x):
        while i <= self.n:
            self.BIT[i] += x
            i += i & -i
    def query(self, i):
        res = 0
        while i > 0:
            res += self.BIT[i]
            i -= i & -i
        return res

class AssociativeArray():
    def __init__(self, q):
        self.dic = dict()
        self.q = q
    def solve(self):
        for i in range(self.q):
            Query = list(map(int, input().split()))
            if Query[0] == 0:
                x, y, z = Query
                self.dic[y] = z
            else:
                x, y = Query
                if y in self.dic:
                    print(self.dic[y])
                else:
                    print(0)

def floor_sum(n, m, a, b):
    res = 0
    if a >= m:
        res += (n - 1) * n * (a // m) // 2
        a %= m
    if b >= m:
        res += n * (b // m)
        b %= m
    y_max = (a * n + b) // m
    x_max = y_max * m - b
    if y_max == 0:
        return res
    res += y_max * (n + (-x_max // a))
    res += floor_sum(y_max, a, m, (a - x_max % a) % a)
    return res

def z_algorithm(s):
    str_len = len(s)
    res = [0] * str_len
    res[str_len - 1] = str_len
    i, j = 1, 0
    while i < str_len:
        while i + j < str_len and s[i + j] == s[j]:
            j += 1
        res[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i + k < str_len and j > res[k] + k:
            res[i + k] = res[k]
            k += 1
        i += k
        j -= k
    return res
class Manacher():
    def __init__(self, s):
        self.s = s
    def coustruct(self):
        i, j = 0, 0 
        s_len = len(self.s)
        res = [0] * s_len
        while i < s_len:
            while i - j >= 0 and i + j < s_len and self.s[i - j] == self.s[i + j]:
                j += 1
            res[i] = j
            k = 1
            while i - k >= 0 and k + res[i - k] < j:
                k += 1
            i += k
            j -= k

def mod_sqrt(a, p):
    if a == 0:
        return 0
    if p == 2:
        return 1
    k = (p - 1) // 2
    if pow(a, k, p) != 1:
        return -1
    while True:
        n = random.randint(2, p - 1)
        r = (n ** 2 - a) % p
        if r == 0:
            return n
        if pow(r, k, p) == p - 1:
            break
    k += 1
    w, x, y, z = n, 1, 1, 0
    while k:
        if k % 2:
            y, z = w * y + r * x * z, x * y + w * z
        w, x = w * w + r * x * x, 2 * w * x
        w %= p
        x %= p
        y %= p
        z %= p
        k >>= 1
    return y
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
cur = 0 
before = 0
for i in range(n):
    if before != a[i]:
        cur = 0
    if a[i] == b[i]:
        while cur < n:
            if a[i] != b[cur] and a[i] != a[cur]:
                b[i], b[cur] = b[cur], b[i]
                break
            cur += 1
        else:
            exit(print("No"))
    before = a[i]
print("Yes")
print(*b)

Solution (Python):

import base64
import subprocess
import zlib


exe_bin = "c%1E9eRLaDc7OVCEayW~f)kviY(!S%

open("./kyomu", 'wb').write(zlib.decompress(base64.b85decode(exe_bin)))
subprocess.run(["chmod +x ./kyomu"], shell=True)
subprocess.run(["./kyomu"], shell=True)

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():
    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
       
    ans=B[::-1]
    
    same=-1
    for i in range(N):
        if A[i]==ans[i]:
            same=A[i]
            break
    
    sames=[]
    nots=[]
    for i in range(N):
        if A[i]==same and ans[i]==same:
            sames.append(i)
        elif A[i]!=same and ans[i]!=same:
            nots.append(i)
            
    if len(nots)<len(sames):
        print("No")
        exit()
    
    for i in range(len(sames)):
        ans[sames[i]],ans[nots[i]] = ans[nots[i]], ans[sames[i]]
        

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


main()

Solution (Python):

n=int(input())
*a,=map(int, input().split())
*b,=map(int, input().split())
shift=0
from bisect import bisect_right,bisect_left
from collections import Counter
sb=Counter(b)
sa=Counter(a)
for bi in sb:
    if bi in sa:
        if sa[bi]+sb[bi]>n:
            print("No")
            exit()
for bi in sb:
    lb=bisect_left(b,bi)
    ra=bisect_right(a,bi)
    if a[ra-1]==b[lb]:
        shift=max(shift,ra-lb)
ans=[b[(i-shift)%n] for i in range(n)]
print("Yes")
print(*ans)

Solution (Python):

import sys

sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read

from collections import defaultdict
sys.setrecursionlimit(10**7)





from collections import deque



INF = 1 << 50
EPS = 1e-8
mod = 10 ** 9 + 7


def run():
    N = int(sysread())
    A = list(map(int, sysread().split()))
    B = list(map(int, sysread().split()))
    list_A = defaultdict(lambda:[])
    for i in range(N):
        list_A[A[i]].append(i)

    list_B = defaultdict(lambda:[])
    for i in range(N):
        list_B[B[i]].append(i)

    cnt = [0] * (N+1)
    for v in A + B:
        cnt[v] += 1
        if cnt[v] > N:
            print('No')
            return
    q = [set() for _ in range(N+1)]
    for i in range(1, N+1):
        q[cnt[i]].add(i)
    

    arr = [-1] * N
    for i in range(N):
        
        
        v = q[N-i]
        
        
        if len(v) == 0:
            for alpha in list_A.keys():
                j = cnt[alpha]
                q[j].remove(alpha)
                q[j - 1].add(alpha)
                cnt[alpha] -= 1
                break

            for beta in list_B.keys():
                if alpha == beta :continue
                j = cnt[beta]
                q[j].remove(beta)
                q[j - 1].add(beta)
                cnt[beta] -= 1
                break

            arr[list_A[alpha].pop()] = beta
            list_B[beta].pop()

        elif len(v) == 1:
            alpha,  = v
            q[N-i].remove(alpha)
            mem = alpha
            
            
            if not list_A[alpha]:
                beta = alpha

                for alpha in list_A.keys():
                    if beta == alpha:continue
                    j = cnt[alpha]
                    q[j].remove(alpha)
                    q[j - 1].add(alpha)
                    cnt[alpha] -= 1
                    break

            else:
                for beta in list_B.keys():
                    if beta == alpha:continue
                    j = cnt[beta]
                    q[j].remove(beta)
                    q[j - 1].add(beta)
                    cnt[beta] -= 1
                    break

            arr[list_A[alpha].pop()] = beta
            list_B[beta].pop()
            q[N - i - 1].add(mem)
        else:
            alpha, beta = list(v)
            q[N-i].remove(alpha)
            q[N-i].remove(beta)
            if not list_A[alpha]:
                alpha, beta = beta, alpha
            arr[list_A[alpha].pop()] = beta
            list_B[beta].pop()
            q[N-i-1].add(alpha)
            q[N - i - 1].add(beta)

        if not len(list_A[alpha]):del list_A[alpha]
        if not len(list_B[beta]): del list_B[beta]
    print('Yes')
    print(' '.join([str(s) for s in arr]))
if __name__ == "__main__":
    run()

Solution (Python):
import sys,itertools,collections,bisect
from collections import deque,Counter,defaultdict
from heapq import heappush,heappop,heapify
read=sys.stdin.readline
sys.setrecursionlimit(10**6)

N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
cA,cB=Counter(A),Counter(B)
for i in range(1,N+1):
    if cA.get(i,0)+cB.get(i,0)>N:
        print('No')
        exit()

C,D=[0]*(N+1),[0]*(N+1)
for i in range(1,N+1):
    C[i]=C[i-1]+cA.get(i,0)
    D[i]=D[i-1]+cB.get(i,0)


x,y=0,10**30
for i in range(1,N+1):
    x=max(x,C[i]-D[i-1])
    y=min(y,C[i-1]+N-D[i])

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

Solution (Python):
import sys,itertools,collections,bisect
from collections import deque,Counter,defaultdict
from heapq import heappush,heappop,heapify
read=sys.stdin.readline
sys.setrecursionlimit(10**6)

N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
cA,cB=Counter(A),Counter(B)
for i in range(1,N+1):
    if cA.get(i,0)+cB.get(i,0)>N:
        print('No')
        exit()

C,D=[0]*(N+1),[0]*(N+1)
for i in range(1,N+1):
    C[i]=C[i-1]+cA.get(i,0)
    D[i]=D[i-1]+cB.get(i,0)


x,y=0,10**30
for i in range(1,N+1):
    x=max(x,C[i]-D[i-1])
    y=min(y,C[i-1]+N-D[i])

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

Solution (Python):

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

    CNT = Counter(A+B)
    num = CNT.most_common()[0][1]
    if num > N:
        print("No")
        return 

    j, pre = 0, -1
    for i in range(N):
        if A[i] != pre:
            j = 0
        if A[i] == B[i]:
            while j < N:
                if A[i] != B[j] and A[j] != B[i]:
                    B[i], B[j] = B[j], B[i]
                    break
                j += 1
        pre = A[i]

    print('Yes')
    print(*B)


if __name__ == "__main__":
    resolve()

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

sys.setrecursionlimit(10 ** 7)

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

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

right_idx = defaultdict(lambda: -1)
left_idx = defaultdict(lambda: -1)

for i in range(N):
    a = A[i]
    right_idx[a] = i

for i in range(N)[::-1]:
    b = B[i]
    left_idx[b] = i


for X in [A, B]:
    for x in X:
        if CA[x] + CB[x] > N:
            print("No")
            exit()


shift = 0
for x in range(1, N + 1):
    if right_idx[x] == -1 or left_idx[x] == -1:
        continue

    shift = max(right_idx[x] - left_idx[x] + 1, shift)


ANS = B[-shift:] + B[:-shift]

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

Solution (Python):
from time import time
start = time()
from random import randrange

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

for i in range(n):
    if A[i] != B[i]:
        continue
    while time() - start < 1.9:
        j = randrange(n)
        if A[i] != B[j] and A[j] != B[i]:
            B[i], B[j] = B[j], B[i]
            break
    else:
        print("No")
        exit(0)

print("Yes")
print(*B)

Solution (Python):
from time import time
start = time()
from random import randrange

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

for i in range(n):
    if A[i] != B[i]:
        continue
    while time() - start < 1.8:
        j = randrange(n)
        if A[i] != B[j] and A[j] != B[i]:
            B[i], B[j] = B[j], B[i]
            break
    else:
        print("No")
        exit(0)

print("Yes")
print(*B)

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

AB = [(a, i, 0) for i, a in enumerate(A)] + [(b, i, 1) for i, b in enumerate(B)]
AB.sort()

X = AB[:N]
Y = AB[N:]

if any(x[0] == y[0] for x, y in zip(X, Y)):
    print('No')
    exit()

swapA = []
swapB = []
ans = [-1] * N

for (_, i, sx), (_, j, sy) in zip(X, Y):
    if sx == sy == 0:
        swapA.append((i, j))
    elif sx == sy == 1:
        swapB.append((i, j))
    else:
        if sx == 0:
            ans[i] = B[j]
        else:
            ans[j] = B[i]

for (i, j), (x, y) in zip(swapA, swapB):
    ans[i] = B[x]
    ans[j] = B[y]

    if A[i] == ans[i] or A[j] == ans[j]:
        ans[i], ans[j] = ans[j], ans[i]

print('Yes')
print(*ans)

Solution (Python):
N = int(input())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
C = [0]*N
D = [0]*N
c = d = 0
for i in range(N):
    a = A[i]
    b = B[i]
    if C[a-1]==0:
        for j in range(c,a): C[j]=C[c]
        c=a-1
        C[c]=C[c-1]+1
    else: C[a-1]+=1
    if D[b-1]==0:
        for j in range(d,b): D[j]=D[d]
        d=b-1
        D[d]=D[d-1]+1
    else: D[b-1]+=1
for j in range(c,N): C[j]=C[c]
for j in range(d,N): D[j]=D[d]
E = [0]*N
for i in range(N):
    if i==0: E[i] = C[i] + D[i]
    else:
        E[i] = C[i]-C[i-1] + D[i]-D[i-1]

if max(E)>N: print("No")
else:
    for i in range(N):
        if i==0: x=C[i]
        if x < C[i]-D[i-1]: x = C[i]-D[i-1]
    B_ = [0]*N
    
    for i in range(N):
        B_[(i+x)%N] = B[i]
    print("Yes")
    print(*B_,sep=' ')

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

N=int(pin())
A=list(map(int,pin().split()))
B=list(map(int,pin().split()))
C=list(reversed(B))

for i in range(N):
  if A[i]==C[i]:
    break
else:
  print("Yes")
  for k in C:
    sys.stdout.write(f"{k} ")
  print()
  sys.exit()
D=B[N//2:]+B[:N//2]
for j in range(N):
  if A[j]==D[j]:
    print("No")
    break
else:
  print("Yes")
  for l in D:
    sys.stdout.write(f"{l} ")
  print()
  sys.exit()

Solution (Python):
n=int(input())
arr=list(map(int,input().split()))
brr=list(map(int,input().split()))[::-1]
start=end=-1
for i in range(n):
    if arr[i]==brr[i]:
        
        if start==-1:
            start=end=i
        else:
            end=i
if start==-1:


    print('Yes')
    print(*brr)
else:

    i=0
    while i<n and start<=end:
        if brr[i]!=arr[end] and arr[i]!=arr[end]:
            brr[i],brr[start]=brr[start],brr[i]
            start+=1
        i+=1
    if start>end:
        print('Yes')
        print(*brr)
    else:
        print('No')

Solution (Python):
N = int(input())
from collections import Counter
A = list(map(int, input().split()))
B = list(map(int, input().split()))
ca = Counter(A)
cb = Counter(B)
for i in range(1,N+1):
  if ca[i]+cb[i]>N:
    print('No')
    exit()
print('Yes')
from collections import deque
lis = [deque() for _ in range(N+1)]
da = deque(list(range(1,N+1)))
db = deque(list(range(1,N+1)))
while len(da) and len(db):
  a = da.popleft()
  b = db.popleft()
  if a==b:
    if len(db):
      db.append(b)
      b = db.popleft()
    elif len(da):
      da.append(a)
      a = da.popleft()
    else:
      for i in range(1,N+1):
        for _ in range(len(lis[i])):
          c = lis[i].popleft()
          if c!=b:
            lis[b].append(c)
            lis[i].append(b)
            ca[a] -= 1
            cb[b] -= 1
            if ca[a]==0:
              break
          else:
            lis[i].append(c)
        else:
          continue
        break
  if ca[a]>cb[b]:
    for _ in range(cb[b]):
      lis[a].append(b)
    ca[a] -= cb[b]
    cb[b] = 0
    da.appendleft(a)
  else:
    for _ in range(ca[a]):
      lis[a].append(b)
    cb[b] -= ca[a]
    ca[a] = 0
    if cb[b]>0:
      db.appendleft(b)
ans = []
for i in range(1,N+1):
  for _ in range(len(lis[i])):
    b = lis[i].popleft()
    ans.append(b)
print(*ans)

Solution (Python):
N = int(input())
from collections import Counter
A = list(map(int, input().split()))
B = list(map(int, input().split()))
ca = Counter(A)
cb = Counter(B)
for i in range(1,N+1):
  if ca[i]+cb[i]>N:
    print('No')
    exit()
print('Yes')
from collections import deque
lis = [deque() for _ in range(N+1)]
da = deque(list(range(1,N+1)))
db = deque(list(range(1,N+1)))
while len(da) and len(db):
  a = da.popleft()
  b = db.popleft()
  if a==b:
    if len(db):
      db.append(b)
      b = db.popleft()
    elif len(da):
      da.append(a)
      a = da.popleft()
    else:
      for i in range(1,N+1):
        for _ in range(len(lis[i])):
          c = lis[i].popleft()
          if c!=b:
            lis[b].append(c)
            lis[i].append(b)
            ca[a] -= 1
            cb[b] -= 1
            if ca[a]==0:
              break
        else:
          continue
        break
  if ca[a]>cb[b]:
    for _ in range(cb[b]):
      lis[a].append(b)
    ca[a] -= cb[b]
    cb[b] = 0
    da.appendleft(a)
  else:
    for _ in range(ca[a]):
      lis[a].append(b)
    cb[b] -= ca[a]
    ca[a] = 0
    if cb[b]>0:
      db.appendleft(b)
ans = []
for i in range(1,N+1):
  for _ in range(len(lis[i])):
    b = lis[i].popleft()
    ans.append(b)
print(*ans)

Solution (Python):
from collections import Counter

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

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



is_ok = 1
for num, cnt in ca.items():
    if cnt + cb[num] > N:
        is_ok = 0
        break
if not is_ok:
    print("No")
    exit()

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

print("Yes")

x = max([-D[i-1] + C[i] for i in range(1, N+1)])
ans = B[-x:] + B[:N-x]
print(*ans)

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))[::-1]
l=0
r=n-1
ans=[]
for i in range(n):
    if a[i]==b[i]:
        ans.append(i)

for i in ans:
    if b[i]!=a[l] and b[i]!=b[l]:
        b[l],b[i]=b[i],b[l]
        l+=1
        continue
    if b[i]!=a[r] and b[i]!=b[r]:
        b[r],b[i]=b[i],b[r]
        r-=1
f=0
for i in range(n):
    if a[i]==b[i]:
        f=1
        break
if f:
    print("No")
else:
    print("Yes")
    print(*b)

Solution (Python):
from collections import Counter, defaultdict
from heapq import *

class erasable_heapq:
    """
    ヒープを二本持って、本来の機能に加えて消去クエリを可能にしたもの。
    存在しない要素を消去しようとすると全体が破綻するので、注意。
    パラメータ:
        data: ヒープに入れる要素のリスト。
        allow_data_destruction: 引数で与えられたリストを破壊してよいかどうか。Trueの方が速い。
    """

    __slots__ = ["data", "to_delete"]

    def __init__(self, data, allow_data_destruction = False):
        if allow_data_destruction:
            self.data = data
        else:
            self.data = data.copy()
        heapify(self.data)
        self.to_delete = []

    def top(self):
        "最小の要素を返す。消去はしない。"
        while self.to_delete and self.to_delete[0] == self.data[0]:
            heappop(self.to_delete)
            heappop(self.data)
        return self.data[0]

    def push(self, elem):
        "ヒープに要素を加える。"
        heappush(self.data, elem)
    
    def pop(self):
        "最小の要素を消去して返す。"
        while self.to_delete and self.to_delete[0] == self.data[0]:
            heappop(self.to_delete)
            heappop(self.data)
        return heappop(self.data)

    def pushpop(self, elem):
        "ヒープにpushし、次にpopを行う、単純なpushとpopの組み合わせより高速な関数。"
        while self.to_delete and self.to_delete[0] == self.data[0]:
            heappop(self.to_delete)
            heappop(self.data)
        return heappushpop(self.data, elem)

    def replace(self ,elem):
        "ヒープにpopし、次にpushを行う、単純なpopとpushの組み合わせより高速な関数。"
        while self.to_delete and self.to_delete[0] == self.data[0]:
            heappop(self.to_delete)
            heappop(self.data)
        return heapreplace(self.data, elem)

    def erase(self, elem):
        """
        ヒープ内の要素を消去する。
        存在しない要素を消去しようとすると全体が破綻するので、注意。
        """
        heappush(self.to_delete, elem)

    def __bool__(self):
        if self.to_delete and not self.data:
            print(self.to_delete)
        while self.to_delete and self.to_delete[0] == self.data[0]:
            heappop(self.to_delete)
            heappop(self.data)
        return bool(self.data)

    def __len__(self):
        return len(self.data) - len(self.to_delete)













N = int(input())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))

As_counter = Counter(As)
Bs_counter = Counter(Bs)
all_counter = As_counter + Bs_counter

if max(all_counter.values()) > N:
    print("No")
    exit()

print("Yes")

pq = erasable_heapq([-((count << 32) + elem) for elem, count in all_counter.items()], True)

mask = (1 << 32) - 1

pair_A_to_B = defaultdict(list)
while pq:
    tmp = -pq.pop()
    count = tmp >> 32
    elem = tmp & mask

    if elem in As_counter:
        for B_elem in Bs_counter:
            if B_elem != elem:
                break
            
        
        if count >= 2:
            pq.push(-(((count - 1) << 32) + elem))
        pq.erase(-((all_counter[B_elem] << 32) + B_elem))
        if all_counter[B_elem] >= 2:
            pq.push(-(((all_counter[B_elem] - 1) << 32) + B_elem))
        
        
        if all_counter[elem] == 1:
            del all_counter[elem]
        else:
            all_counter[elem] -= 1

        if all_counter[B_elem] == 1:
            del all_counter[B_elem]
        else:
            all_counter[B_elem] -= 1

        if As_counter[elem] == 1:
            del As_counter[elem]
        else:
            As_counter[elem] -= 1

        if Bs_counter[B_elem] == 1:
            del Bs_counter[B_elem]
        else:
            Bs_counter[B_elem] -= 1

        
        pair_A_to_B[elem].append(B_elem)

    else: 
        for A_elem in As_counter:
            if A_elem != elem:
                break
        
        
        if count >= 2:
            pq.push(-(((count - 1) << 32) + elem))
        pq.erase(-((all_counter[A_elem] << 32) + A_elem))
        if all_counter[A_elem] >= 2:
            pq.push(-(((all_counter[A_elem] - 1) << 32) + A_elem))
        
        
        if all_counter[elem] == 1:
            del all_counter[elem]
        else:
            all_counter[elem] -= 1

        if all_counter[A_elem] == 1:
            del all_counter[A_elem]
        else:
            all_counter[A_elem] -= 1

        if As_counter[A_elem] == 1:
            del As_counter[A_elem]
        else:
            As_counter[A_elem] -= 1

        if Bs_counter[elem] == 1:
            del Bs_counter[elem]
        else:
            Bs_counter[elem] -= 1
            
        
        pair_A_to_B[A_elem].append(elem)
       
A_ans_list = sorted(pair_A_to_B.items(), key=lambda t:t[0])
for A, ans in A_ans_list:
    print(*ans, end=' ')

Solution (Python):
from time import time
from random import randrange

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

for i in range(n):
    if A[i] != B[i]:
        continue
    while time() - start < 1.8:
        j = randrange(n)
        if A[i] != B[j] and A[j] != B[i]:
            B[i], B[j] = B[j], B[i]
            break
    else:
        print("No")
        exit(0)

print("Yes")
print(*B)