You are given a positive integer $m$ and two integer sequence: $a=[a_1, a_2, \ldots, a_n]$ and $b=[b_1, b_2, \ldots, b_n]$. Both of these sequence have a length $n$.

Permutation is a sequence of $n$ different positive integers from $1$ to $n$. For example, these sequences are permutations: $[1]$, $[1,2]$, $[2,1]$, $[6,7,3,4,1,2,5]$. These are not: $[0]$, $[1,1]$, $[2,3]$.

You need to find the non-negative integer $x$, and increase all elements of $a_i$ by $x$, modulo $m$ (i.e. you want to change $a_i$ to $(a_i + x) \bmod m$), so it would be possible to rearrange elements of $a$ to make it equal $b$, among them you need to find the smallest possible $x$.

In other words, you need to find the smallest non-negative integer $x$, for which it is possible to find some permutation $p=[p_1, p_2, \ldots, p_n]$, such that for all $1 \leq i \leq n$, $(a_i + x) \bmod m = b_{p_i}$, where $y \bmod m$ — remainder of division of $y$ by $m$.

For example, if $m=3$, $a = [0, 0, 2, 1], b = [2, 0, 1, 1]$, you can choose $x=1$, and $a$ will be equal to $[1, 1, 0, 2]$ and you can rearrange it to make it equal $[2, 0, 1, 1]$, which is equal to $b$.


-----Input-----

The first line contains two integers $n,m$ ($1 \leq n \leq 2000, 1 \leq m \leq 10^9$): number of elemens in arrays and $m$.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i < m$).

The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($0 \leq b_i < m$).

It is guaranteed that there exists some non-negative integer $x$, such that it would be possible to find some permutation $p_1, p_2, \ldots, p_n$ such that $(a_i + x) \bmod m = b_{p_i}$.


-----Output-----

Print one integer, the smallest non-negative integer $x$, such that it would be possible to find some permutation $p_1, p_2, \ldots, p_n$ such that $(a_i + x) \bmod m = b_{p_i}$ for all $1 \leq i \leq n$.


-----Examples-----
Input
4 3
0 0 2 1
2 0 1 1

Output
1

Input
3 2
0 0 0
1 1 1

Output
1

Input
5 10
0 0 0 1 2
2 1 0 0 0

Output
0

Source: codeforces | Difficulty: MEDIUM
Tags: Sorting

Complete search


Solutions:
list1 = input().split()
n = int(list1[0])
m = int(list1[1])
a = input().split()
b = input().split()
a = [int(x) for x in a]
b = [int(x) for x in b]
a = sorted(a)
b = sorted(b)
list2 = a
i = 0
l = n
d = 0
mind = 100000000000
while i < l:
	j = 0
	equal = True
	d = (b[i] - a[0]) % m
	for k in range(l):
		if i + j == l:
			j = -i
		if (b[i + j] - list2[k]) % m != d:
			equal = False
			break
		j += 1
	if equal:
		if d < mind:
			mind = d
	i += 1
print(mind)


(n, m) = (int(x) for x in input().strip().split())
a = [int(x) for x in input().strip().split()]
b = [int(x) for x in input().strip().split()]
f = False
b.sort()
ans = m
for i in a:
	x = (b[0] - i) % m
	c = [(el + x) % m for el in a]
	c.sort()
	if b == c:
		ans = min(ans, x)
print(ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
min_x = m
for i in range(n):
	x = (b[0] - a[i]) % m
	c = a.copy()
	for j in range(n):
		c[j] = (c[j] + x) % m
	c.sort()
	if c == b:
		min_x = min(min_x, x)
print(min_x)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
x = []
for i in range(n):
	x.append((b[0] - a[i]) % m)
x = list(set(x))
for i in x:
	q = []
	for j in range(n):
		q.append((a[j] + i) % m)
	q.sort()
	if q == b:
		print(i)
		break


(n, mod) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
da = {}
db = {}
mp = {}
for i in range(n):
	if a[i] in da:
		da[a[i]] += 1
	else:
		da[a[i]] = 1
	if b[i] in db:
		db[b[i]] += 1
	else:
		db[b[i]] = 1
x = 9999999999999
for i in range(n):
	if db[b[i]] == da[a[0]]:
		if b[i] >= a[0]:
			tmp = b[i] - a[0]
		else:
			tmp = b[i] + mod - a[0]
		if tmp > x:
			continue
		flag = 1
		for j in range(n):
			k = (a[j] + tmp) % mod
			if k in mp:
				mp[k] += 1
			else:
				mp[k] = 1
			if k not in db or mp[k] > db[k]:
				flag = 0
				break
		if flag == 1:
			x = min(x, tmp)
		mp.clear()
print(x)


import sys
import math

def run(i, dif):
	global m
	for j in range(len(a)):
		indB = (j + i) % len(a)
		if b[indB] < a[j]:
			newDif = m - a[j] + b[indB]
		else:
			newDif = b[indB] - a[j]
		if newDif != dif:
			return False
	return True
(n, m) = list(map(int, sys.stdin.readline().split()))
a = list(map(int, sys.stdin.readline().split()))
b = list(map(int, sys.stdin.readline().split()))
a = sorted(a)
b = sorted(b)
ans = math.inf
for i in range(len(b)):
	if a[0] > b[i]:
		dif = m - a[0] + b[i]
	else:
		dif = b[i] - a[0]
	if run(i, dif):
		ans = min(ans, dif)
print(ans)


nums = input().split()
n = int(nums[0])
m = int(nums[1])
a = [int(i) for i in input().split()]
b = [int(j) for j in input().split()]
x_arr = []
true_x = float('inf')
for num in a:
	x = (b[0] - num) % m
	x_arr.append(x)
for x in x_arr:
	t_a = [(t + x) % m for t in a]
	if sorted(t_a) == sorted(b):
		true_x = min(true_x, x)
print(true_x)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
da = {}
db = {}
for i in range(n):
	if da.get(a[i], 0) == 0:
		da[a[i]] = 1
	else:
		da[a[i]] += 1
	if db.get(b[i], 0) == 0:
		db[b[i]] = 1
	else:
		db[b[i]] += 1
count = 0
l1 = sorted(set(a))
l2 = sorted(set(b))
min1 = 100000000000000
while count < len(l1):
	flag = True
	if l1[0] > l2[count]:
		k = m - l1[0] + l2[count]
	else:
		k = l2[count] - l1[0]
	for i in range(len(l1)):
		if da[l1[i]] != db[l2[(i + count) % len(l1)]] or (l1[i] + k) % m != l2[(i + count) % len(l1)]:
			flag = False
			break
	if flag == True:
		if l1[0] > l2[count]:
			k = m - l1[0] + l2[count]
		else:
			k = l2[count] - l1[0]
		if k < min1:
			min1 = k
		break
	count += 1
print(min1)


def main():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	b.sort()
	answer = []
	for i in range(n):
		x = (b[0] - a[i]) % m
		tmp = a.copy()
		for idx in range(n):
			tmp[idx] = (tmp[idx] + x) % m
		tmp.sort()
		if tmp == b:
			answer.append(x)
	print(min(answer))
	return
main()


def solve(a, b, m, n):
	ans = m
	for i in range(n):
		x = (m + b[i] - a[0]) % m
		for j in range(n):
			if (a[j] + x) % m != b[(i + j) % n]:
				break
		else:
			ans = min(ans, x)
	return ans
(n, m) = map(int, input().split())
a = sorted(list(map(int, input().split())))
b = sorted(list(map(int, input().split())))
print(solve(a, b, m, n))


from collections import Counter
(n, m) = map(int, input().split())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
cnta = list(Counter(a).items())
cntb = list(Counter(b).items())
cnta.sort()
cntb.sort()
ret = []
l = len(cnta)
for i in range(l):
	diff = (cntb[i][0] - cnta[0][0]) % m
	for j in range(1, l):
		if cnta[j][1] != cntb[(j + i) % l][1] or (cntb[(j + i) % l][0] - cnta[j][0]) % m != diff:
			break
	else:
		ret.append(diff)
print(min(ret))


def check(x, a, b, m):
	res = [(a[i] + x) % m for i in range(n)]
	res.sort()
	b_copy = b.copy()
	b_copy.sort()
	if b_copy == res:
		return x
	else:
		return m + 2
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
min_ = m + 1
for i in range(n):
	if b[0] - a[i] < 0:
		x = m - abs(b[0] - a[i])
	else:
		x = b[0] - a[i]
	if 0 <= check(x, a, b, m) < min_:
		min_ = check(x, a, b, m)
print(min_)


from collections import defaultdict, deque
from itertools import permutations
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
from copy import deepcopy
int_input = lambda : int(stdin.readline())
string_input = lambda : stdin.readline()
multi_int_input = lambda : map(int, stdin.readline().split())
multi_input = lambda : stdin.readline().split()
list_input = lambda : list(map(int, stdin.readline().split()))
string_list_input = lambda : list(string_input())
MOD = pow(10, 9) + 7
(n, m) = multi_int_input()
a = list_input()
b = list_input()
a.sort()
b.sort()
possible_x = set([])
ans = []
for i in range(n):
	possible_x.add((b[0] - a[i]) % m)
for x in possible_x:
	temp = []
	for i in range(n):
		temp.append((a[i] + x) % m)
	temp.sort()
	if temp == b:
		ans.append(x)
print(min(ans))


import sys
input = sys.stdin.readline
(N, M) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
B.sort()
A.sort()
ans = 10 ** 14
for l in range(N):
	delta = (B[0] - A[l]) % M
	ok = True
	for i in range(N - l):
		if (B[i] - A[i + l] - delta) % M != 0:
			ok = False
			break
	for i in range(N - l, N):
		if (B[i] - A[i + l - N] - delta) % M != 0:
			ok = False
			break
	if ok:
		ans = min(ans, delta)
print(ans)


from sys import stdin, stdout
from math import gcd, sqrt, factorial
from collections import deque, defaultdict
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 0 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
(n, m) = R()
a = sorted(R())
b = sorted(R())
p = sorted([(i - a[0]) % m for i in b])
for i in p:
	if b == sorted([(a[j] + i) % m for j in range(n)]):
		exit(print(i))


n = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
e = sorted(b)
pos = [(b[i] - a[0]) % n[1] for i in range(n[0])]
for i in pos:
	s = []
	for j in a:
		s.append((j + i) % n[1])
	d = sorted(s)
	if d == e:
		print(i)
		break


from collections import defaultdict
s = input()
(n, m) = list(map(int, s.split()))
a = list(map(lambda x: int(x) % m, input().split()))
b = list(map(lambda x: int(x) % m, input().split()))
d1 = defaultdict(int)
d2 = defaultdict(int)
for x in a:
	d1[x] += 1
for x in b:
	d2[x] += 1
x1 = sorted(d1.items(), key=lambda x: (x[1], x[0]))
x2 = sorted(d2.items(), key=lambda x: (x[1], x[0]))
for i in range(len(x2)):
	d = (x2[i][0] - x1[0][0]) % m
	flag = True
	for j in range(len(x1)):
		if x1[j][1] != d2[(x1[j][0] + d) % m]:
			flag = False
			break
	if flag:
		print(d)
		break


(n, m) = list(map(int, input().split()))
aa = list(map(int, input().split()))
bb = list(map(int, input().split()))
ss = {}
for i in bb:
	try:
		ss[i] += 1
	except:
		ss[i] = 1
mi = float('inf')
for i in range(n):
	x = (bb[i] - aa[0]) % m
	cc = [(a + x) % m for a in aa]
	tt = {}
	for i in cc:
		try:
			tt[i] += 1
		except:
			tt[i] = 1
	if ss == tt:
		mi = min(mi, x)
print(mi)


import sys
(n, m) = [int(i) for i in sys.stdin.readline().split()]
a = [int(i) for i in sys.stdin.readline().split()]
b = [int(i) for i in sys.stdin.readline().split()]
x = []
b.sort()
maxb = b[-1]
for i in range(n):
	if maxb >= a[i]:
		x.append(maxb - a[i])
	else:
		x.append(maxb + m - a[i])
x.sort()
ans = -1
for i in x:
	a1 = a[:]
	for j in range(n):
		a1[j] = (a1[j] + i) % m
	a1.sort()
	if a1 == b:
		ans = i
		break
print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
from fractions import Fraction
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
(n, m) = Ri()
a = Ri()
b = Ri()
b.sort()
maxx = INF
for i in range(len(a)):
	x = (b[0] - a[i]) % m
	temp = [(i + x) % m for i in a]
	temp.sort()
	if temp == b:
		maxx = min(maxx, x)
print(maxx)


from collections import Counter, OrderedDict
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = sorted(list(map(int, input().split())))
count_a = Counter(a)
count_b = Counter(b)
c_b = count_b.most_common(1)[0][1]
m_b = count_b.most_common(1)[0][0]
res = []
for d in count_a.most_common(n):
	if d[1] == c_b:
		m_a = d[0] % m
		res.append(m_b - m_a if m_b >= m_a else m_b + m - m_a)
	if d[1] < c_b:
		break
final_res = []
res = sorted(res)
for r in res:
	if sorted([(x + r) % m for x in a]) == b:
		print(r)
		break


import sys
import math
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
b += b
last = m
for i in range(n):
	x = (b[i] - a[0] + m) % m
	flag = 1
	for j in range(n):
		if (a[j] + x) % m != b[i + j]:
			flag = 0
			break
	if flag:
		last = min(last, x)
print(last)


import sys
import collections
import heapq
import math
import bisect
input = sys.stdin.readline

def rints():
	return map(int, input().strip().split())

def rstr():
	return input().strip()

def rint():
	return int(input().strip())

def rintas():
	return [int(i) for i in input().strip().split()]

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
(n, m) = rints()
a = rintas()
b = rintas()
b.sort()
ans = float('inf')
for i in range(n):
	k = (b[i] - a[0]) % m
	tmp = []
	for j in a:
		tmp.append((j + k) % m)
	tmp.sort()
	if tmp == b:
		ans = min(ans, k)
print(ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b = sorted(b)
ans = -1
for i in range(n):
	aux = []
	if b[i] < a[0]:
		x = b[i] + m - a[0]
	else:
		x = b[i] - a[0]
	for j in range(n):
		aux.append((a[j] + x) % m)
	aux = sorted(aux)
	if b == aux:
		ans = x
		if ans != -1:
			ans = min(ans, x)
		else:
			ans = x
print(ans)


import sys, math, string, bisect
input = sys.stdin.readline
from collections import deque, defaultdict, Counter
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())

def find_gt(a, x):
	i = bisect_right(a, x)
	if i != len(a):
		return a[i]
	raise ValueError

def rightRotate(lists, num):
	output_list = []
	for item in range(len(lists) - num, len(lists)):
		output_list.append(lists[item])
	for item in range(0, len(lists) - num):
		output_list.append(lists[item])
	return output_list

def fun(a, b, j, x, k, ans):
	g = b[j:] + b[:j]
	s = a[:]
	for i in range(len(a)):
		s[i] = (s[i] + x) % k
	if s == g:
		ans.append(x)
(n, k) = M()
a = L()
b = L()
a.sort()
b.sort()
ad = defaultdict(int)
bd = defaultdict(int)
ad = Counter(a)
bd = Counter(b)
if a == b:
	print(0)
else:
	a = sorted(list(set(a)))
	b = sorted(list(set(b)))
	l = []
	m = []
	for i in a:
		l.append(ad[i])
	for i in b:
		m.append(bd[i])
	done = 0
	ans = []
	for j in range(len(m)):
		if l[0] == m[j]:
			if a[0] % k < b[j]:
				x = b[j] - a[0] % k
			elif a[0] % k > b[j]:
				x = k - a[0] % k + b[j]
			g = fun(a, b, j, x, k, ans)
	print(min(ans))


def solve(n, m, a, b):
	temp = []
	b = sorted(b)
	for i in range(n):
		x = (b[0] - a[i]) % m
		temp.append(x)
	mini = int(1000000000.0)
	for x in temp:
		ans = []
		for i in range(n):
			ans.append((a[i] + x) % m)
		ans = sorted(ans)
		if ans == b:
			mini = min(mini, x)
	print(mini)
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
solve(n, m, a, b)


def fastio():
	import sys
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
from math import gcd
from collections import defaultdict as dd, Counter as C
(n, m) = I()
a = sorted(I())
b = sorted(I())
ac = C(a)
bc = C(b)
k = bc[b[0]]
ans = 10 ** 20

def check(x):
	t = a[:]
	for i in range(n):
		t[i] = (t[i] + x) % m
	tc = C(t)
	return tc == bc
for i in ac:
	if ac[i] == k and check((b[0] - i) % m):
		ans = min(ans, (b[0] - i) % m)
print(ans)


import os
import sys
from io import BytesIO, IOBase
from collections import Counter

def main():
	(n, m) = map(int, input().split(' '))
	a = list(map(int, input().split(' ')))
	b = list(map(int, input().split(' ')))
	if sorted(a) == sorted(b):
		print(0)
	else:
		ans = m
		for x in range(n):
			temp = (b[0] - a[x] + m) % m
			boss = list(a)
			for y in range(n):
				boss[y] = (boss[y] + temp) % m
			if sorted(boss) == sorted(b):
				ans = min(ans, temp)
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


n = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
pos = [(b[i] - a[0]) % n[1] for i in range(n[0])]
for i in pos:
	s = [(a[j] + i) % n[1] for j in range(n[0])]
	s.sort()
	if s == b:
		print(i)
		break


import collections
import math
(n, m) = [int(s) for s in input().split()]
a = [int(s) for s in input().split()]
b = [int(s) for s in input().split()]
a.sort()
b.sort()
b = collections.deque(b)

def check(a, b):
	minus = b[0] - a[0]
	if minus < 0:
		x = minus + m
		minus2 = minus
	else:
		x = minus
		minus2 = x - m
	flag = 0
	for i in range(1, n):
		if b[i] - a[i] == minus:
			if flag:
				return False
		elif b[i] - a[i] == minus2:
			flag = 1
		else:
			return False
	return True
for i in range(n):
	if check(a, b):
		minus = b[0] - a[0]
		if minus < 0:
			x = minus + m
		else:
			x = minus
		print(x)
		break
	b.append(b.popleft())


def main():
	from sys import stdin
	(n, m) = list(map(int, stdin.readline().split()))
	a = list(map(int, stdin.readline().split()))
	b = list(map(int, stdin.readline().split()))
	ans = 2 * m
	(counta, countb) = ({}, {})
	for i in range(n):
		if a[i] in counta:
			counta[a[i]] += 1
		else:
			counta[a[i]] = 1
		if b[i] in countb:
			countb[b[i]] += 1
		else:
			countb[b[i]] = 1
	choice = counta[a[0]]
	work1 = list(filter(lambda x: counta[x] == choice, counta.keys()))
	work2 = list(filter(lambda x: countb[x] == choice, countb.keys()))
	assert len(work1) == len(work2)
	hope = set()
	for jt in range(len(work2)):
		hope.add((work2[jt] - work1[0]) % m)
	for h in hope:
		if (ans == 2 * m or (h < ans and h != 0)) and sorted(list(map(lambda x: (x + h) % m, work1))) == sorted(work2):
			ans = min(ans, h)
	if ans == 2 * m:
		print(0)
	else:
		print(ans)
main()


def __starting_point():
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	a.sort()
	b.sort()
	mindiff = float('inf')
	for (i, num) in enumerate(a):
		diff = (b[-1] - num) % m
		_a = [(i + diff) % m for i in a]
		_a.sort()
		if _a == b:
			mindiff = min(mindiff, diff)
	print(mindiff)
__starting_point()


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
diff = [0] * n
for i in range(n):
	diff[i] = b[i] - a[0]
for i in range(n):
	if diff[i] < 0:
		diff[i] = diff[i] + m
ans = 10 ** 9 + 1
if a == b:
	print(0)
else:
	for i in range(n):
		temp = []
		for j in range(n):
			temp.append((a[j] + diff[i]) % m)
		temp.sort()
		if temp == b:
			ans = min(ans, diff[i])
	print(ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
da = {}
db = {}
for i in a:
	da[i] = da.get(i, 0) + 1
for i in b:
	db[i] = db.get(i, 0) + 1
x = 1000000001
ca = {}
cb = {}
for i in da:
	try:
		ca[da[i]].append(i)
	except:
		ca[da[i]] = [i]
for i in db:
	try:
		cb[db[i]].append(i)
	except:
		cb[db[i]] = [i]
ans = {}
for i in ca:
	for j in ca[i]:
		for k in cb[i]:
			ans[(k - j) % m] = ans.get((k - j) % m, 0) + 1
l = len(da)
for i in ans:
	if ans[i] == l:
		x = min(x, i)
print(x)


import math
import os
import sys
input = lambda : sys.stdin.readline().strip('\r\n')

def cin():
	return sys.stdin.readline().strip('\r\n')

def fora():
	return list(map(int, sys.stdin.readline().strip().split()))

def string():
	return sys.stdin.readline().strip()

def cout(ans):
	sys.stdout.write(str(ans))

def endl():
	sys.stdout.write(str('\n'))

def ende():
	sys.stdout.write(str(' '))

def main():
	(n, m) = map(int, cin().split())
	a = fora()
	b = fora()
	a.sort()
	b.sort()
	mp1 = {}
	mp2 = {}
	mp1 = dict.fromkeys(a, 0)
	mp2 = dict.fromkeys(b, 0)
	for i in a:
		mp1[i] += 1
	for i in b:
		mp2[i] += 1
	if mp1 == mp2:
		cout(0)
	else:
		mint = n + 1
		el = 0
		for i in mp1:
			if mint >= mp1[i]:
				mint = mp1[i]
				el = i
		l = []
		for i in mp2:
			if mp2[i] == mint:
				l.append(i)
		for i in l:
			x = 0
			mp3 = {}
			if i >= el:
				x = i - el
			else:
				x = m - (el - i)
			for i in mp1:
				t = (i + x) % m
				mp3[t] = mp1[i]
			if mp2 == mp3:
				cout(x)
				break
main()


import os
import sys
from collections import Counter
from io import BytesIO, IOBase
import math

def solve(n, m, a1, a2):
	(a1c, a1s) = (Counter(a1), set(a1))
	(a2c, a2s) = (Counter(a2), set(a2))
	a2_counter_sorted = Counter(sorted(a2))
	mc = a2c.most_common(1)[0]
	ks = []
	while True:
		try:
			tc = a1c.most_common(1)[0]
		except:
			break
		if tc[1] != mc[1]:
			break
		a1c.pop(tc[0])
		k = mc[0] - tc[0] if mc[0] - tc[0] >= 0 else m + (mc[0] - tc[0])
		if Counter(sorted([(a + k) % m for a in a1])) == a2_counter_sorted:
			ks.append(k)
	return min(ks)

def main():
	(n, m) = map(int, input().strip().split())
	a1 = list(map(int, input().strip().split()))
	a2 = list(map(int, input().strip().split()))
	print(solve(n, m, a1, a2))
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline()
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def readnumbers(zero=0):
	conv = ord if py2 else lambda x: x
	A = []
	numb = zero
	sign = 1
	i = 0
	s = sys.stdin.buffer.read()
	try:
		while True:
			if s[i] >= b'0'[0]:
				numb = 10 * numb + conv(s[i]) - 48
			elif s[i] == b'-'[0]:
				sign = -1
			elif s[i] != b'\r'[0]:
				A.append(sign * numb)
				numb = zero
				sign = 1
			i += 1
	except:
		pass
	if s and s[-1] >= b'0'[0]:
		A.append(sign * numb)
	return A
main()


(n, m) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
a = sum(A)
b = sum(B)
t = a - b
B.sort()
P = [(B[0] - A[i]) % m for i in range(n)]
P.sort()
for i in P:
	if (a % m - b % m + n * i % m) % m == 0:
		X = [(j + i) % m for j in A]
		X.sort()
		if X == B:
			print(i)
			quit()


from collections import Counter

def get_exes(a, mx, m):
	exes = set()
	for num in a:
		if num != mx:
			if mx > num:
				exes.add(mx - num)
			else:
				exes.add(m - num + mx)
		else:
			exes.add(0)
	return exes

def solve(a, b, m):
	counts_b = Counter(b)
	exes = get_exes(a, max(b), m)
	for x in sorted(list(exes)):
		counts_a = Counter([(num + x) % m for num in a])
		if counts_a == counts_b:
			return x
(n, m) = list(map(int, input().strip().split(' ')))
a = list(map(int, input().strip().split(' ')))
b = list(map(int, input().strip().split(' ')))
print(solve(a, b, m))


import sys
input = sys.stdin.readline
from collections import defaultdict
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
cnta = defaultdict(int)
cntb = defaultdict(int)
for x in a:
	cnta[x] += 1
for x in b:
	cntb[x] += 1
aa = list(set(a))
bb = list(set(b))
assert len(aa) == len(bb)
nn = len(aa)
ans = 10 ** 20
for k in range(nn):
	add = (bb[k] - aa[0] + m) % m
	ok = True
	for i in range(nn):
		x = aa[i]
		y = (x + add) % m
		if cnta[x] != cntb[y]:
			ok = False
			break
	if ok:
		ans = min(ans, add)
print(ans)


(n, m) = map(int, input().split())
a = sorted(map(int, input().split()))
b = sorted(map(int, input().split()))
a_difs = [a[i + 1] - a[i] for i in range(n - 1)]
a_difs.append((a[0] - a[n - 1]) % m)
b_difs = [b[i + 1] - b[i] for i in range(n - 1)]
b_difs = b_difs + [(b[0] - b[n - 1]) % m] + b_difs
answer = m
for i in range(n):
	ok = True
	for j in range(n):
		if a_difs[j] != b_difs[i + j]:
			ok = False
			break
	if ok:
		answer = min(answer, (b[i] - a[0]) % m)
print(answer)


import math
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
fin = 100000000000
for i in range(n):
	ax = a[i:] + a[:i]
	ans = True
	if b[0] >= ax[0]:
		x = (b[0] - ax[0]) % m
	else:
		x = (b[0] + m - ax[0]) % m
	for i in range(n):
		if b[i] >= ax[i]:
			y = (b[i] - ax[i]) % m
			if y == x:
				continue
			else:
				ans = False
				break
		else:
			y = (b[i] + m - ax[i]) % m
			if y == x:
				continue
			else:
				ans = False
				break
	if ans == True:
		fin = min(fin, x)
print(fin)


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
minimum = m
a.sort()
b.sort()
for i in range(0, n):
	temp = (b[i] - a[0]) % m
	flag = True
	for j in range(1, n):
		if not temp == (b[(i + j) % n] - a[j]) % m:
			flag = False
			break
		flag = True
	if flag:
		minimum = min(minimum, temp)
print(minimum)


(n, m) = map(int, input().split())
a = [int(o) for o in input().split()]
b1 = [int(o) for o in input().split()]
a = sorted(a)
b1 = sorted(b1)
c = b1[-1]
jhand = []
for i in range(n):
	if c >= a[i]:
		b = c - a[i]
		lol = [0] * n
		for i in range(n):
			lol[i] = (a[i] + b) % m
		lol.sort()
		if lol == b1:
			jhand.append(b)
	else:
		b = c + m - a[i]
		lol = [0] * n
		for i in range(n):
			lol[i] = (a[i] + b) % m
		lol.sort()
		if lol == b1:
			jhand.append(b)
print(min(jhand))


(n, m) = map(int, input().split())
arr = list(map(int, input().split()))
brr = list(map(int, input().split()))
carr = arr[:]
brr.sort()
flag = 0
ans = -1
for i in range(n):
	x = (brr[0] - arr[i] + m) % m
	for j in range(n):
		carr[j] = (carr[j] + x) % m
	carr.sort()
	for j in range(n):
		if carr[j] != brr[j]:
			flag = 1
			break
	if flag == 0:
		if ans == -1:
			ans = x
		else:
			ans = min(ans, x)
	carr = arr[:]
	flag = 0
print(ans)


def inp():
	return map(int, stdin.readline().split())

def arr_inp():
	return [int(x) for x in stdin.readline().split()]
from sys import *
from collections import *
from math import *
(n, m) = inp()
(a, b) = [arr_inp() for i in range(2)]
(a1, b1) = (Counter(a), Counter(b))
(a, b, ans) = (deque(sorted(set(a))), deque(sorted(set(b))), inf)
for i in range(len(b)):
	(flag, diff) = (1, (b[0] - a[0]) % m)
	for j in range(len(b)):
		if a1[a[j]] == b1[b[j]] and (b[j] - a[j]) % m == diff:
			continue
		if a1[a[j]] != b1[b[j]] or (b[j] - a[j]) % m != diff:
			flag = 0
			break
	if flag:
		ans = min(ans, diff)
	a.rotate(-1)
print(ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
a.sort()
ans = 100000000000000
for i in range(n):
	if a[i] <= b[0]:
		x = b[0] - a[i]
	else:
		x = m - a[i] + b[0]
	if x < ans:
		f = True
		for j in range(n):
			if (a[(i + j + 1) % n] + x) % m != b[(j + 1) % n]:
				f = False
				break
		if f == True:
			ans = x
print(ans)


from sys import stdin, stdout
from collections import deque
(n, m) = map(int, stdin.readline().split())
alist = list(map(int, stdin.readline().split()))
blist = list(map(int, stdin.readline().split()))
bcounts = {}
for b in blist:
	bcounts[b] = bcounts.get(b, 0) + 1
bcount2i = {}
for (i, c) in bcounts.items():
	bcount2i.setdefault(c, []).append(i)
acounts = {}
for a in alist:
	acounts[a] = acounts.get(a, 0) + 1
acount2i = {}
for (i, c) in acounts.items():
	acount2i.setdefault(c, []).append(i)
(minc, minalist) = (None, None)
for (c, alist) in acount2i.items():
	if not minc or len(alist) < len(minalist):
		(minc, minalist) = (c, alist)
a = minalist[0]
minbs = deque(bcount2i[minc])
ans = 0
while True:
	b = minbs.popleft()
	if b < a:
		minbs.append(b + m)
		continue
	diff = b - a
	found = True
	for (oa, c) in acounts.items():
		if bcounts.get((oa + diff) % m, -1) != c:
			found = False
			break
	if found:
		ans = diff
		break
stdout.write('{}'.format(ans))


from collections import Counter, deque
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
(cnt_a, cnt_b) = (Counter(a), Counter(b))
a = deque(sorted(set(a)))
b = sorted(set(b))
ans = 10 ** 18
for _ in range(len(a)):
	delta = (b[0] - a[0]) % m
	if all(((y - x) % m == delta and cnt_a[x] == cnt_b[y] for (x, y) in zip(a, b))):
		ans = min(ans, delta)
	a.rotate(-1)
print(ans)


import sys
import math
input = sys.stdin.readline
(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
best = 10 ** 12
for i in range(len(a)):
	x = b[0] - a[i]
	if x < 0:
		x += m
	ok = 1
	c = []
	for j in range(len(a)):
		c.append((a[j] + x) % m)
	if sorted(c) == b:
		best = min(best, x)
print(best)


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
ans = m
from bisect import *
for i in range(n):
	x = (b[i] - a[0]) % m
	if x >= ans:
		continue
	aa = [(a[j] + x) % m for j in range(n)]
	aa.sort()
	if b == aa and x < ans:
		ans = x
print(ans)


from collections import Counter
((n, m), a, b) = (list(map(int, input().split())) for _ in '012')
c = Counter(b)
for x in sorted(((m + i - a[0]) % m for i in c)):
	if Counter(((i + x) % m for i in a)) == c:
		print(x)
		exit(0)


from collections import Counter

def perm(d1, d2):
	k1 = sorted(d1.keys())
	k2 = sorted(d2.keys())
	init_offset = k2[0] - k1[0]
	if init_offset < 0:
		return False
	for i in range(len(k1)):
		if d1[k1[i]] != d2[k2[i]]:
			return False
		offset = k2[i] - k1[i]
		if offset != init_offset:
			return False
	return True
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = dict(Counter(a))
d = dict(Counter(b))
while not perm(c, d):
	lowest = min(d.keys())
	d[lowest + m] = d[lowest]
	del d[lowest]
k1 = sorted(c.keys())
k2 = sorted(d.keys())
print(min(d.keys()) - min(c.keys()))


def check(i, j, dj):
	val = d[i][j]
	while i < n:
		if d[i][j] == val:
			i += 1
			j += dj
			j %= n
		else:
			break
	if i == n:
		return True
	return False
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
d = [[0 for i in range(n)] for i in range(n)]
for i in range(n):
	for j in range(n):
		d[i][j] = (b[j] - a[i]) % m
ans = []
for x in range(n):
	(i, j) = (0, x)
	if check(i, j, 1) or check(i, j, -1):
		ans.append(d[i][j])
print(min(ans))


from collections import Counter
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
cnt_b = Counter(b)
x = a[0]
for y in b:
	z = (y - x) % m
	cnt_a = Counter(((z + _) % m for _ in a))
	if cnt_a == cnt_b:
		print(z)
		break


(n, m) = map(int, input().split())
list1 = list(map(int, input().split()))
list2 = list(map(int, input().split()))
list1.sort()
list2.sort()
temp = list()
for i in range(n):
	x = (list2[0] - list1[i]) % m
	temp.append(x)
temp.sort()
for i in range(len(temp)):
	temp2 = list()
	f1 = 0
	for j in range(n):
		temp2.append((list1[j] + temp[i]) % m)
	temp2.sort()
	for j in range(n):
		if temp2[j] != list2[j]:
			f1 = 1
			break
	if f1 == 0:
		print(temp[i])
		break


from collections import defaultdict as dd
dic = dd(int)
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in b:
	dic[i] += 1
seti = set()
for i in range(len(b)):
	ins = b[0] - a[i]
	if ins < 0:
		seti.add(ins + m)
	else:
		seti.add(ins)
lis = list(seti)
lis.sort()
for i in lis:
	dic2 = dic.copy()
	flag = 0
	for j in range(len(a)):
		if dic2[(a[j] + i) % m] != 0:
			dic2[(a[j] + i) % m] -= 1
		else:
			flag = 1
			break
	if flag == 1:
		continue
	else:
		print(i)
		break


import sys
input = sys.stdin.buffer.readline
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
res = 10 ** 20
for i in range(n):
	flag = True
	x = (b[i] - a[0]) % m
	for j in range(n):
		if (a[j] + x) % m != b[(j + i) % n]:
			flag = False
			break
	if flag and x < res:
		res = x
print(res)


R = lambda : map(int, input().split())
s = sorted
(n, m) = R()
(a, b) = (s(R()), s(R()))
print(min(((x - a[0]) % m for (i, x) in enumerate(b) if [(y + x - a[0]) % m for y in a] == b[i:] + b[:i])))


from collections import defaultdict, deque
import sys, heapq, bisect, math, itertools, string, queue, copy, time
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
mod = 10 ** 9 + 7
eps = 10 ** (-7)

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))

def inpl_str():
	return list(sys.stdin.readline().split())
(N, M) = inpl()
aa = inpl()
bb = inpl()
aa.sort()
bb.sort()
a0 = aa[0]
ans = 10 ** 10
for b in set(bb):
	x = (b - a0) % M
	aa_dush = sorted([(a + x) % M for a in aa])
	for (a, b) in zip(bb, aa_dush):
		if a != b:
			break
	else:
		ans = min(ans, x)
print(ans)


import collections
(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
x = set()
for i in range(n):
	if b[0] - a[i] >= 0:
		x.add(b[0] - a[i])
	else:
		x.add(m + b[0] - a[i])
for i in x:
	o = []
	for j in a:
		o.append((j + i) % m)
	if collections.Counter(o) == collections.Counter(b):
		print(i)
		break


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

def ii():
	return int(readline())

def mi():
	return map(int, readline().rstrip().split())

def li():
	return list(readline().rstrip())

def lmi():
	return list(map(int, readline().rstrip().split()))

def end(*arg):
	print(*arg)
	sys.exit()

def main():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	b.sort()
	answer = []
	for i in range(n):
		x = (b[0] - a[i]) % m
		tmp = a.copy()
		for idx in range(n):
			tmp[idx] = (tmp[idx] + x) % m
		tmp.sort()
		if tmp == b:
			answer.append(x)
	print(min(answer))
	return
main()


import math, sys
from collections import Counter, defaultdict, deque
from sys import stdin, stdout
input = stdin.readline
lili = lambda : list(map(int, sys.stdin.readlines()))
li = lambda : list(map(int, input().split()))
I = lambda : int(input())
S = lambda : input().strip()
(n, m) = li()
a = li()
b = li()
a.sort()
b.sort()
ans = m + 1
for i in range(0, n):
	d = (b[i] - a[0] + m) % m
	c = [0] * n
	for j in range(0, n):
		c[j] = (a[j] + d) % m
	c.sort()
	if b == c:
		ans = min(ans, d)
print(ans)


def solve(a, b, n, m):
	a.sort()
	b.sort()
	res = m
	for i in range(n):
		delta = ((b[i] - a[0]) % m + m) % m
		ok = True
		for j in range(n):
			d = ((b[(j + i) % n] - a[j]) % m + m) % m
			if d != delta:
				ok = False
				break
		if ok == True:
			res = min(res, delta)
	return res
(n, m) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
print(solve(a, b, n, m))


import sys
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
l = []
for i in range(len(a)):
	x = (b[0] - a[i]) % m
	l.append(x)
l = list(set(l))
for i in range(len(l)):
	q = []
	for j in range(len(a)):
		q.append((a[j] + l[i]) % m)
	if sorted(q) == b:
		print(l[i])
		sys.exit()


import collections
(n, m) = (int(x) for x in input().split())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
deltas = sorted({(b - A[0] + m) % m for b in set(B)})
A_counter = collections.Counter(A)
B_counter = collections.Counter(B)
for d in deltas:
	if B_counter == {(k + d) % m: v for (k, v) in A_counter.items()}:
		print(d)
		break


(n, m) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
b.sort()
resp = b[len(b) - 1] + m
for i in range(n):
	lista = []
	tmp = (b[i] - a[0]) % m
	for e in a:
		lista.append((e + tmp) % m)
	lista.sort()
	if lista == b:
		resp = min(resp, tmp)
print(resp)


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
fixed = b[0]
candidates = []
for i in range(n):
	temp = []
	x = (fixed - a[i] + m) % m
	for j in range(n):
		temp.append((a[j] + x) % m)
	if sorted(temp) == sorted(b):
		candidates.append(x)
print(min(candidates))


import sys
R = lambda : map(int, input().split())
lis = lambda : [int(i) for i in input().split()]
s = sorted
(n, m) = R()
a = lis()
b = lis()
a.sort()
b.sort()
possi = [(b[0] - a[i]) % m for i in range(n)]
possi.sort()
for x in possi:
	new = [(a[i] + x) % m for i in range(n)]
	new.sort()
	if new == b:
		print(x)
		sys.exit(0)
print(0)


from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
from collections import Counter, defaultdict
from collections import deque
from functools import cmp_to_key
import math
import heapq
import re

def sin():
	return input()

def ain():
	return list(map(int, sin().split()))

def sain():
	return input().split()

def iin():
	return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	s = set()
	for p in range(2, n + 1):
		if prime[p]:
			s.add(p)
	return s

def readTree(n, m):
	adj = [deque([]) for _ in range(n + 1)]
	for _ in range(m):
		(u, v) = ain()
		adj[u].append(v)
		adj[v].append(u)
	return adj

def main():
	(n, m) = ain()
	a = ain()
	b = ain()
	b.sort()
	s = set()
	for i in range(n):
		s.add((b[-1] - a[i]) % m)
	for i in s:
		q = deque([])
		for j in range(n):
			q.append((a[j] + i) % m)
		if b == sorted(q):
			print(i)
			break
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
if os.getcwd() == 'D:\\code':
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
from collections import Counter
(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a1 = Counter(a)
b1 = Counter(b)
a1k = sorted(list(a1.keys()))
b1k = sorted(list(b1.keys()))
a1n = len(a1)
b1n = len(b1)
f = 0
out = sys.maxsize
for i in range(a1n):
	s = 0
	for j in range(i, i + a1n):
		if b1[b1k[j % a1n]] == a1[a1k[j - i]]:
			if j - i > 0 and (b1k[j % a1n] - b1k[(j - 1) % a1n]) % m == a1k[j - i] - a1k[j - i - 1]:
				s += 1
			elif j - i == 0:
				s += 1
	if s == a1n:
		out = min(out, (b1k[i] - a1k[0]) % m)
print(out)


def check(n, m, c, d):
	lst = list()
	for i in range(n):
		(result, flag) = (-1, True)
		for j in range(0, n):
			cur = (d[(i + j) % n] - c[j]) % m
			if result == -1:
				result = cur
			elif result != cur:
				flag = False
				break
		if flag:
			lst.append(result)
	return min(lst)
(n, m) = [int(i) for i in input().split()]
c = [int(i) for i in input().split()]
d = [int(i) for i in input().split()]
print(check(n, m, sorted(c), sorted(d)))


from collections import defaultdict

def ok(x):
	t = a[:]
	for i in range(n):
		t[i] = (t[i] + x) % mod
	return sorted(t) == b
(n, mod) = map(int, input().split())
a = list(map(int, input().split()))
b = sorted(list(map(int, input().split())))
countA = defaultdict(int)
countB = defaultdict(int)
for i in range(n):
	countA[a[i]] += 1
	countB[b[i]] += 1
check = None
for val in a:
	if countA[val] != countB[val]:
		check = val
		break
ans = {0}
if check != None:
	for i in range(n):
		if check > b[i]:
			x = b[i] + mod - check
			ans.add(x)
		elif b[i] > check:
			x = b[i] - check
			ans.add(x)
ret = float('inf')
for x in ans:
	if ok(x):
		ret = min(ret, x)
print(ret)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
res = m
for i in b:
	x = (i - a[0]) % m
	if res <= x:
		continue
	temp = []
	for j in a:
		temp.append((j + x) % m)
	temp.sort()
	if temp == b:
		res = x
print(res)


(n, m) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
B.sort()
p = set([(B[0] - a + m) % m for a in A])
for x in p:
	tmp = [(a + x) % m for a in A]
	tmp.sort()
	if tmp == B:
		print(x)
		break


(a, b) = map(int, input().split())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
aram = []
for j in l1:
	aram.append((l2[0] - j) % b)
aram = list(set(aram))
l2.sort()
for ma in aram:
	nl = [(x + ma) % b for x in l1]
	nl.sort()
	if nl == l2:
		print(ma)
		break


import sys
input = sys.stdin.readline
from collections import deque
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
a = deque(a)
b = deque(b)
ans = 0
for _ in range(n):
	if a == b:
		break
	f = 1
	for j in range(n - 1):
		if b[j + 1] - a[j + 1] != b[j] - a[j]:
			f = 0
			break
	if f:
		if b[0] > a[0]:
			print(ans + b[0] - a[0])
			exit()
		else:
			print(ans + b[0] - a[0] + m)
			exit()
	p = m - a[-1]
	ans += p
	ww = 0
	for j in range(n):
		a[j] += p
		if a[j] == m:
			ww = n - j
			break
	for j in range(ww):
		a.pop()
		a.appendleft(0)
print(ans)


def shift():
	a = A.pop(0)
	A.append(a)
	a = A1.pop(0)
	A1.append(a)

def count(A):
	c = A[0]
	n = 0
	A0 = []
	A1 = [A[0]]
	for i in range(len(A)):
		if c == A[i]:
			n += 1
		else:
			A0.append(n)
			A1.append(A[i])
			n = 1
			c = A[i]
	A0.append(n)
	return (A0, A1)

def check(x):
	for i in range(len(A1)):
		if (A1[i] + x) % m != B1[i]:
			return False
	return True
(n, m) = map(int, input().split())
turns = 0
A0 = sorted(list(map(int, input().split())))
B0 = sorted(list(map(int, input().split())))
if A0 == B0:
	print(0)
else:
	(A, A1) = count(A0)
	(B, B1) = count(B0)
	turns = 0
	x = m + 1
	while turns < n:
		if A == B:
			x1 = (m + B1[-1] - A1[-1]) % m
			if x1 < x and check(x1):
				x = x1
		shift()
		turns += 1
	print(x)


import sys
from collections import Counter
reader = (map(int, line.split()) for line in sys.stdin)
input = reader.__next__
(n, m) = input()
a = list(input())
b = list(input())

def add_equal(a, b, n, m):
	check = Counter(b)
	compare = Counter(a)
	if check == compare:
		return 0
	x_cand = set(((b[0] - ai) % m for ai in a))
	for x in sorted(x_cand):
		check_curr = check.copy()
		for ai in a:
			bj = (ai + x) % m
			check_curr[bj] -= 1
			if check_curr[bj] == 0:
				check_curr.pop(bj)
		if not check_curr:
			return x
ans = add_equal(a, b, n, m)
print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
dicta = {}
dictb = {}
for j in range(n):
	resa = a[j] % m
	resb = b[j] % m
	if not resa in dicta:
		dicta[resa] = 1
	elif resa in dicta:
		dicta[resa] += 1
	if not resb in dictb:
		dictb[resb] = 1
	elif resb in dictb:
		dictb[resb] += 1
repa = [(dicta[k], k) for k in dicta.keys()]
repa.sort(key=lambda x: x[1])
repb = [(dictb[k], k) for k in dictb.keys()]
repb.sort(key=lambda x: x[1])
minsofar = m + 1
for j in range(len(repa)):
	broke = False
	init = (repb[j][1] - repa[0][1]) % m
	for s in range(len(repa)):
		if not ((repb[(s + j) % len(repb)][1] - repa[s][1]) % m == init and repb[(s + j) % len(repb)][0] == repa[s][0]):
			broke = True
			break
	if broke == False:
		val = (repb[j][1] - repa[0][1]) % m
		if val < minsofar:
			minsofar = val
print(minsofar)


I = lambda : int(input())
ID = lambda : map(int, input().split())
IL = lambda : list(ID())
(n, m) = ID()
a = IL()
b = IL()
a.sort()
b.sort()
ans = m
for i in range(n):
	f = True
	if a[0] == b[i]:
		x = 0
	elif a[0] > b[i]:
		x = b[i] - a[0] + m
	else:
		x = b[i] - a[0]
	j = i
	l = 1
	while l < n:
		j = (j + 1) % n
		if (a[l] + x) % m != b[j]:
			f = False
		l += 1
	if f:
		ans = min(ans, x)
print(ans)


from collections import Counter

def Compare(a, b):
	for i in a:
		if b[i] != a[i]:
			return False
	return True
(n, m) = [int(i) for i in input().split()]
min = m
a = [int(i) for i in input().split()]
comparator = a[0]
b = [int(i) for i in input().split()]
b = Counter(b)
for i in b:
	if comparator > i:
		diff = m - comparator + i
	else:
		diff = i - comparator
	c = Counter([(i + diff) % m for i in a])
	if diff < min and Compare(b, c):
		min = diff
print(min)


from sys import stdin, stdout
import sys
from bisect import bisect_left, bisect_right
import heapq
from collections import Counter
(n, m) = stdin.readline().strip().split(' ')
(n, m) = (int(n), int(m))
a = list(map(int, stdin.readline().strip().split(' ')))
b = list(map(int, stdin.readline().strip().split(' ')))
a = sorted(a, reverse=True)
b = sorted(b, reverse=True)
da = dict(Counter(b))
d = {}
ans = 1 << 64
if a == b:
	ans = 0
for i in b:
	diff = abs(a[0] - i)
	if a[0] < i:
		for j in a:
			kk = (j + diff) % m
			if kk in d:
				d[kk] += 1
			else:
				d[kk] = 1
		if d == da:
			ans = min(ans, diff)
	else:
		for j in a:
			kk = (j + m - diff) % m
			if kk in d:
				d[kk] += 1
			else:
				d[kk] = 1
		if d == da:
			ans = min(ans, m - diff)
	d = {}
stdout.write(str(ans) + '\n')


import os
import sys
from io import BytesIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import Counter

def mod(x, y):
	if x >= y:
		return x - y
	return x
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
bb = list(map(int, input().split()))
t = Counter(a)
b = Counter(bb)
x = t[a[0]]
sdvigs = []
for el in b:
	if b[el] == x:
		sdvigs.append(el)
minshift = m
for el in sdvigs:
	shift = (el - a[0]) % m
	for el in t:
		if b[mod(el + shift, m)] != t[el]:
			break
	else:
		minshift = min(minshift, shift)
print(minshift)


import sys
from math import gcd
from heapq import heappop
from heapq import heappush
from heapq import heapify
from bisect import insort
from bisect import bisect_right
from bisect import bisect_left
from sys import stdin, stdout
from collections import defaultdict, deque
from math import log2, ceil, floor
inp = lambda : int(input())
sip = lambda : input()
mulip = lambda : map(int, input().split())
lst = lambda : list(map(int, input().split()))
slst = lambda : list(sip())
arr2d = lambda x: [[int(j) for j in input().split()] for i in range(x)]
odds = lambda l: len(list(filter(lambda x: x % 2 != 0, l)))
evens = lambda l: len(list(filter(lambda x: x % 2 == 0, l)))
mod = pow(10, 9) + 7
Judge = 0
if Judge:
	sys.stdin = open('input.in', 'r')
(n, m) = mulip()
a = lst()
b = lst()
a = sorted(a)
b = sorted(b)
if m == 1 or a == b:
	print(0)
else:
	ans = pow(10, 9) + 7
	mn = min(b)
	cnt = 0
	for i in b:
		if i == mn:
			cnt += 1
	d = defaultdict(int)
	for i in a:
		d[i] += 1
	for i in d:
		if d[i] == cnt:
			rem = m - i + mn
			x = list(a)
			for i in range(n):
				x[i] = (x[i] + rem) % m
			x = sorted(x)
			if x == b:
				ans = min(ans, rem)
	print(ans % m)


(n, m) = map(int, input().split())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
l = sorted(b)
A = sorted(list(set(a)))
B = sorted(list(set(b)))
ans = m - 1
for i in range(0, len(B)):
	k = abs(B[i] - A[0])
	h = []
	for j in range(0, len(a)):
		h.append((a[j] + k) % m)
	if sorted(h) == l:
		ans = min(ans, k)
	k2 = m - abs(B[i] - A[0])
	h = []
	for j in range(0, len(a)):
		h.append((a[j] + k2) % m)
	if sorted(h) == l:
		ans = min(ans, k2)
print(ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
bd = {}
for bi in b:
	if bi not in bd:
		bd[bi] = 0
	bd[bi] += 1
ad = {}
for ai in a:
	if ai not in ad:
		ad[ai] = 0
	ad[ai] += 1
xs = []
for bi in bd:
	if a[0] == bi:
		xi = 0
	elif a[0] < bi:
		xi = bi - a[0]
	else:
		xi = bi + m - a[0]
	valid = True
	for ai in ad:
		if (ai + xi) % m not in bd:
			valid = False
		else:
			valid = valid and ad[ai] == bd[(ai + xi) % m]
		if not valid:
			break
	if valid:
		xs.append(xi)
print(min(xs))


(n, m) = map(int, input().split())
a = input().split()
b = input().split()
c = list(set(a))
d = list(set(b))
e = [[0, c[i]] for i in range(len(c))]
f = [[0, d[i]] for i in range(len(d))]
for i in range(len(c)):
	for j in range(n):
		if c[i] == a[j]:
			e[i][0] += 1
for i in range(len(d)):
	for j in range(n):
		if d[i] == b[j]:
			f[i][0] += 1
e.sort()
f.sort()
ans = 10 ** 9 + 1
for i in range(n):
	a[i] = int(a[i])
	b[i] = int(b[i])
a.sort()
b.sort()
for i in range(len(f)):
	if e[0][0] == f[i][0]:
		g = []
		h = (int(f[i][1]) - int(e[0][1])) % m
		for j in range(n):
			g.append((a[j] + h) % m)
		g.sort()
		if g == b:
			ans = min(ans, h)
print(ans)


(n, m) = map(int, input().split(' '))
a = list(map(int, input().split(' ')))
b = list(map(int, input().split(' ')))
a.sort()
b.sort()
ans = m
p = True
for i in range(n):
	x = (m + b[i] - a[0]) % m
	anew = [(a[i] + x) % m for i in range(n)]
	anew.sort()
	if anew == b:
		ans = min(ans, x)
print(ans)


from sys import stdin

def iinput():
	return int(stdin.readline())

def sinput():
	return input()

def minput():
	return map(int, stdin.readline().split())

def linput():
	return list(map(int, stdin.readline().split()))
(n, m) = minput()
a = linput()
b = linput()
b.sort()
x = float('inf')
for e in a:
	temp = (b[0] - e + m) % m
	temp_a = []
	for i in range(n):
		temp_a.append((a[i] + temp) % m)
	temp_a.sort()
	if temp_a == b:
		x = min(x, temp)
print(x)


def makeCntMap(A):
	cnt = {}
	for item in A:
		if item in cnt:
			cnt[item] += 1
		else:
			cnt[item] = 1
	return cnt
(n, m) = map(int, input().split())
A = sorted([int(x) % m for x in input().split()])
B = sorted([int(x) % m for x in input().split()])
cntA = makeCntMap(A)
cntB = makeCntMap(B)
minGuy = list(cntA.keys())[0]
for item in cntA:
	if cntA[item] < cntA[minGuy]:
		minGuy = item
cands = []
for item in cntB:
	if cntB[item] == cntA[minGuy]:
		cands.append(item + m)
ans = m - 1
for item in cands:
	x = (item - minGuy) % m
	arr = sorted([(temp + x) % m for temp in A])
	if arr == B:
		ans = min(ans, x)
print(ans)


from collections import deque
(n, m) = map(int, input().split())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
a.sort()
b.sort()
if a == b:
	print(0)
	exit(0)
q1 = deque()
q2 = deque()
for i in range(n):
	q1.append(a[i])
	q2.append(b[i])
ans = m + 10
for i in range(n):
	t = q1.popleft()
	q1.append(t)
	tmp = (q2[0] - q1[0]) % m
	fin = True
	for j in range(n):
		if (q1[j] + tmp) % m != q2[j]:
			fin = False
			break
	if fin == True:
		ans = min(ans, tmp)
print(ans)


def solve():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	x = [(ele - a[0] + m) % m for ele in b]
	for i in range(n):
		a_ = [(ele + x[i]) % m for ele in a]
		a_.sort()
		b.sort()
		if a_ == b:
			print(x[i])
			break
solve()


import math
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
min_x = math.inf
for i in range(len(b)):
	x = (b[i] - a[0]) % m
	if x < min_x:
		new_a = [(y + x) % m for y in a]
		new_a.sort()
		if new_a == b:
			min_x = x
print(min_x)


import sys
input = sys.stdin.readline

def main():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	b.sort()
	answer = []
	for i in range(n):
		x = (b[0] - a[i]) % m
		tmp = list(map(lambda num: (num + x) % m, a))
		tmp.sort()
		if tmp == b:
			answer.append(x)
	print(min(answer))
	return
main()


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
modArr = []
for i in range(n):
	modArr.append((b[0] - a[i]) % m)
set = list(set(modArr))
for i in set:
	aux = []
	for j in range(n):
		aux.append((a[j] + i) % m)
	aux.sort()
	if aux == b:
		print(i)
		break


import sys, os, io

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

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	for _ in range(1):
		(n, mod) = ria()
		a = ria()
		b = ria()
		a = sorted(a)
		b = sorted(b)
		da = Counter(a)
		db = Counter(b)
		na = []
		c = 0
		t = 0
		counterans = {}
		m = 1
		for i in da:
			c += 1
			for j in db:
				if db[j] == da[i]:
					x1 = j - i
					x2 = mod + j - i
					if x1 >= 0:
						if x1 in counterans:
							counterans[x1] += 1
							m = max(m, counterans[x1])
						else:
							counterans[x1] = 1
					if x2 != x1 and x2 >= 0:
						if x2 in counterans:
							counterans[x2] += 1
							m = max(m, counterans[x2])
						else:
							counterans[x2] = 1
		z = []
		for i in counterans:
			if counterans[i] == m:
				z.append(i)
		z = sorted(z)
		print(z[0])
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


(n, p) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a_elts = {}
b_elts = {}
for i in a:
	a_elts[i] = 0
for i in b:
	b_elts[i] = 0
for i in a:
	a_elts[i] += 1
for i in b:
	b_elts[i] += 1
wyn = 1000000000
for i in b_elts:
	przes = i - a[0] if i >= a[0] else p + i - a[0]
	dick = {}
	for j in a_elts:
		dick[(j + przes) % p] = a_elts[j]
	if dick == b_elts:
		wyn = min(wyn, przes)
print(wyn)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush, heappop, heapify
from itertools import permutations, combinations
mod = int(1000000000.0) + 7
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
out = lambda x: stdout.write(str(x) + '\n')
t = 1
for _ in range(t):
	(n, m) = inp()
	a = list(inp())
	b = list(inp())
	dic = dd(list)
	ct1 = Counter(a)
	ct2 = Counter(b)
	dica = dd(list)
	for i in ct1:
		dica[ct1[i]].append(i)
	dicb = dd(list)
	for i in ct2:
		dicb[ct2[i]].append(i)
	ch = sorted(list(dica.keys()))
	count = dd(int)
	for i in ch:
		for j in dica[i]:
			for jj in dicb[i]:
				diff = (jj - j) % m
				count[diff] += 1
	val = max(list(count.values()))
	ans = float('inf')
	for i in count:
		if count[i] == val:
			ans = min(ans, i)
	out(ans)


import sys
import math as mt
import bisect
input = sys.stdin.readline
t = 1

def solve():
	for i in range(len(ans)):
		d2 = {}
		for j in range(n):
			d2[(l[j] + ans[i]) % m] = d2.get((l[j] + ans[i]) % m, 0) + 1
		if d2 == cnt1:
			return ans[i]
for _ in range(t):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	l1 = list(map(int, input().split()))
	d = {}
	d1 = {}
	cnt = {}
	for i in range(n):
		cnt[l[i]] = cnt.get(l[i], 0) + 1
	cnt1 = {}
	for i in range(n):
		cnt1[l1[i]] = cnt1.get(l1[i], 0) + 1
	for i in cnt:
		if d.get(cnt[i], -1) == -1:
			d[cnt[i]] = []
		d[cnt[i]].append(i)
	for i in cnt1:
		if d1.get(cnt1[i], -1) == -1:
			d1[cnt1[i]] = []
		d1[cnt1[i]].append(i)
	mini = n + 1
	for i in d1:
		if len(d1[i]) < mini:
			mini = len(d1[i])
			ind = i
	ans = []
	for j1 in range(len(d[ind])):
		ans.append((d1[ind][0] - d[ind][j1]) % m)
	ans.sort()
	print(solve())


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
b += b
r = m
for i in range(n):
	x = (b[i] + m - a[0]) % m
	ok = True
	for j in range(n):
		if (a[j] + x) % m != b[i + j]:
			ok = False
			break
	if ok:
		r = min(r, x)
print(r)


def main():
	(n, m) = [int(x) for x in input().split(' ')]
	ais = [int(x) for x in input().split(' ')]
	ais.sort()
	bis = [int(x) for x in input().split(' ')]
	bis.sort()
	diffs = {(bis[0] - ai + 2 * m) % m for ai in ais}
	for diff in sorted(diffs):
		new = list(map(lambda x: (x + diff) % m, ais))
		new.sort()
		if new == bis:
			print(diff)
main()


import math
(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = []
d = []
for i in range(n):
	c.append(a[i] % m)
	d.append(b[i] % m)
c.sort()
d.sort()
ans = math.inf
for i in range(n):
	x = (d[i] - c[0] + m) % m
	val = x
	for j in range(n):
		if (c[j] + x) % m != d[(i + j) % n]:
			val = math.inf
	ans = min(ans, val)
print(ans)


def isvalid(x):
	hashic = hashi.copy()
	for i in ai:
		z = (i + x) % m
		if z not in hashic or hashic[z] == 0:
			return 0
		else:
			hashic[z] -= 1
	return 1
l = input().split()
n = int(l[0])
m = int(l[1])
a = input().split()
ai = [int(i) for i in a]
b = input().split()
bi = [int(i) for i in b]
hashi = dict()
for i in bi:
	if i in hashi:
		hashi[i] += 1
	else:
		hashi[i] = 1
mina = []
for i in range(n):
	x = (bi[i] - ai[0]) % m
	if isvalid(x):
		mina.append(x)
print(min(mina))


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
minimum = 1e+18
for i in range(0, n):
	x = (b[i] - a[0]) % m
	flag = 1
	temp = []
	for j in range(0, n):
		temp.append((a[j] + x) % m)
	temp.sort()
	if temp == b:
		minimum = min(x, minimum)
print(minimum)


import sys
import collections
from collections import Counter
import itertools
import math
import timeit

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	divisors = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				divisors.append(i)
			else:
				divisors.extend([i, n // i])
	return divisors

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def flin(d, x, default=-1):
	left = right = -1
	for i in range(len(d)):
		if d[i] == x:
			if left == -1:
				left = i
			right = i
	if left == -1:
		return (default, default)
	else:
		return (left, right)

def ceil(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def prr(a, sep=' '):
	print(sep.join(map(str, a)))

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)
(n, m) = mi()
a = li()
b = li()
bc = dd()
d = set()
for i in b:
	t = i - a[0] if i >= a[0] else m + i - a[0]
	d.add(t)
	bc[i] += 1
res = 10 ** 10
for i in d:
	ac = dd()
	f = 1
	for el in a:
		t = (el + i) % m
		ac[t] += 1
		if ac[t] > bc[t]:
			f = 0
			break
	if f:
		res = min(res, i)
print(res)


from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
(n, m) = map(int, input().split())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
hash2 = defaultdict(int)
for i in l2:
	hash2[i] += 1
z = l1[0]
ho = []
for i in range(n):
	z1 = l2[i]
	k = z1 - z % m
	x = -1
	if k > 0:
		x = k
	else:
		x = m + k
	hash1 = defaultdict(int)
	for j in range(n):
		hash1[(l1[j] + x) % m] += 1
	flag = 0
	for i in hash1:
		if hash1[i] == hash2[i]:
			continue
		else:
			flag = 1
			break
	if not flag:
		ho.append(x)
ho.sort()
if ho[0] == m:
	ho[0] = 0
print(ho[0])


from collections import Counter

def read_nums():
	return [int(x) for x in input().split()]

def check_match(rs, m, ca, cb):
	for (key, val) in ca.items():
		if not val == cb[(key + rs) % m]:
			return False
	return True

def main():
	(n, m) = read_nums()
	a = [x % m for x in read_nums()]
	b = [x % m for x in read_nums()]
	ca = Counter(a)
	cb = Counter(b)
	ma = sum(a) % m
	mb = sum(b) % m
	options = []
	for elem_a in ca:
		for elem_b in cb:
			rs = (elem_b - elem_a) % m
			if not (ma + rs * n) % m == mb:
				continue
			if check_match(rs, m, ca, cb):
				options.append(rs)
	res = min(options)
	print(res)
main()


(n, m) = map(int, input().split())
from math import *
import sys
input = sys.stdin.readline
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
c = min(b)
mini = 9999999999999
for i in range(n):
	x = c - a[i] % m
	if x < 0:
		x += m
	d = [0 for i in range(n)]
	for j in range(n):
		d[j] = (a[j] + x) % m
	if sorted(d) == sorted(b):
		mini = min(mini, x)
print(mini)


(n, m) = input().split()
n = int(n)
m = int(m)
a = sorted([int(x) for x in input().split()])
b = sorted([int(x) for x in input().split()])
for index in range(n):
	c = a[:n - index]
	d = b[index:n]
	for i in range(n - index):
		if d[i] - c[i] != d[0] - c[0]:
			break
	else:
		x = (d[0] - c[0] + m) % m
		break
print(x)


def kek(A1, A2):
	d1 = {}
	d2 = {}
	for a in A1:
		if a in d1:
			d1[a] += 1
		else:
			d1[a] = 1
	for a in A2:
		if a in d2:
			d2[a] += 1
		else:
			d2[a] = 1
	return d1 == d2
(l, m) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
D1 = {}
D2 = {}
for a in A:
	if a in D1:
		D1[a] += 1
	else:
		D1[a] = 1
for a in B:
	if a in D2:
		D2[a] += 1
	else:
		D2[a] = 1
W = []
for key in D2:
	if D2[key] == D1[A[0]]:
		W.append(key)

def Lol(W, A, B, m):
	for key in W:
		B2 = list(B)
		for i in range(len(B2)):
			B2[i] = (B2[i] + (-key + A[0])) % m
		if kek(A, B2):
			return (key - A[0] + m) % m
print(Lol(W, A, B, m))


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
out = 1000000000.0 + 1
for i in range(n):
	good = True
	dc = {}
	dif = ((b[i] - a[0]) % m + m) % m
	for j in range(n):
		if b[j] in dc:
			dc[b[j]] += 1
		else:
			dc[b[j]] = 1
	for j in range(n):
		if (a[j] + dif) % m in dc and dc[(a[j] + dif) % m] > 0:
			dc[(a[j] + dif) % m] -= 1
		else:
			good = False
			break
	if good:
		out = min(out, dif)
print(out)


def find(key, k, m):
	if m >= k and k >= key:
		n = k - key
	elif m >= k and k < key:
		n = m - (key - k)
	else:
		return -1
	return n

def convert(a, n, m):
	array = []
	for i in a:
		array.append((i + n) % m)
	return array

def compare(a, b):
	a.sort()
	b.sort()
	i = 0
	while i < len(a):
		if a[i] != b[i]:
			return False
		i += 1
	return True
(n, m) = input().split()
n = int(n)
m = int(m)
a = list(map(int, input().split()))
b = list(map(int, input().split()))
hasha = dict()
for i in a:
	if i in hasha:
		hasha[i] += 1
	else:
		hasha[i] = 1
hashb = dict()
for j in b:
	if j in hashb:
		hashb[j] += 1
	else:
		hashb[j] = 1
key = a[0]
minm = 2 ** 31 - 1
for k in hashb:
	if hasha[key] == hashb[k]:
		n = find(key, k, m)
		if n != -1:
			newa = convert(a, n, m)
			if compare(newa, b):
				minm = min(n, minm)
print(minm)


R = lambda : map(int, input().split())
s = sorted
(n, m) = R()
r = range(n)
(a, b) = (s(R()), s(R()) * 2)
print(min(((b[i] - a[0]) % m for i in r if all(((a[j] + b[i] - a[0]) % m == b[i + j] for j in r)))))


R = lambda : map(int, input().split())
s = sorted
(n, m) = R()
(a, b) = (s(R()), s(R()))
x = m
for _ in a:
	b = b[1:] + b[:1]
	z = b[0] - a[0]
	if [(x + z) % m for x in a] == b:
		x = min(x, z % m)
print(x)


from collections import deque
(n, m) = list(map(int, input().split()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))
A.sort()
A = deque(A)
B.sort()
for _ in range(n + 1):
	d = (A[0] - B[0]) % m
	for i in range(1, n):
		if (A[i] - B[i]) % m != d:
			d = -1
			break
	if d != -1:
		print(-d % m)
		return
	x = A.pop()
	A.appendleft(x)
print(-1)


from bisect import *

def check(x):
	global n, m, a, b
	for i in range(1, n):
		if (a[i] + x) % m != b[i]:
			return False
	return True
(n, m) = map(int, input().split())
a = sorted(list(map(int, input().split())))
b = sorted(list(map(int, input().split())))
idx = bisect_left(b, a[0])
b = b[idx:] + b[:idx]
x = 0
for i in range(n):
	if check(b[0] - a[0]):
		x = b[0] - a[0]
		break
	b = b[1:] + b[:1]
print(x if x >= 0 else m + x)


import sys
read = lambda : sys.stdin.readline().strip()
readi = lambda : map(int, read().split())
from collections import defaultdict, deque
(n, m) = readi()
a = list(sorted(readi()))
b = list(sorted(readi()))
ans = deque()
for i in range(n):
	x = b[0] - a[i]
	d = deque()
	if x < 0:
		x += m
	for val in a:
		d.append((val + x) % m)
	if list(sorted(d)) == b:
		ans.append(x)
print(min(ans))


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
d_b = dict()
for x in b:
	if x in d_b:
		d_b[x] += 1
	else:
		d_b[x] = 1
d_a = dict()
for x in a:
	if x in d_a:
		d_a[x] += 1
	else:
		d_a[x] = 1
l = []
for x in d_a:
	for y in d_b:
		if d_a[x] == d_b[y]:
			if x == y:
				l.append(0)
			elif x > y:
				l.append(m - x + y)
			else:
				l.append(y - x)
d_common = dict()
for x in l:
	if x in d_common:
		d_common[x] += 1
	else:
		d_common[x] = 0
print(max(d_common, key=d_common.get))


(n, mo) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
da = {}
db = {}
for i in range(len(a)):
	try:
		da[a[i]] += 1
	except:
		da[a[i]] = 1
	try:
		db[b[i]] += 1
	except:
		db[b[i]] = 1
cona = {}
for i in da.keys():
	try:
		cona[da[i]].append(i)
	except:
		cona[da[i]] = [i]
conb = {}
for i in db.keys():
	try:
		conb[db[i]].append(i)
	except:
		conb[db[i]] = [i]

def check(dif, k1, k2):
	for i in range(len(k1)):
		w = (k1[i] + dif) % mo
		if w not in k2:
			return False
	return True
l = []
for key in cona.keys():
	l.append([len(cona[key]), key])
m = min(l)
k1 = cona[m[1]]
k2 = conb[m[1]]
num = k1[0]
for i in range(len(k2)):
	dif = k2[i] - num
	if dif < 0:
		dif += mo
	dif = dif % mo
	if check(dif, k1, k2):
		print(dif)
		break


import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
from decimal import *
BUFSIZE = 8192
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def main():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	da = collections.Counter([x % m for x in a])
	db = collections.Counter([x % m for x in b])
	sa = sorted(da.items(), key=lambda x: x[1])
	sb = sorted(db.items(), key=lambda x: x[1])
	d = collections.defaultdict()
	for x in sa:
		for y in sb:
			if x[1] == y[1]:
				temp = (y[0] + m - x[0]) % m
				if temp not in d.keys():
					d[temp] = 1
				else:
					d[temp] += 1
	ans = m + 1
	for key in d.keys():
		if d[key] == len(sa):
			ans = min(ans, key)
	print(ans)
main()


(n, m) = map(int, input().split())
a = sorted(list(map(int, input().split())))
b = sorted(list(map(int, input().split())))
mini = float('inf')
for i in range(n):
	x = (b[0] - a[i]) % m
	if sorted([(x + a[j]) % m for j in range(n)]) == b:
		mini = min(mini, x)
print(mini)


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s = set()
x = a[0]
for i in b:
	e = i - x
	if e >= 0:
		s.add(e)
	else:
		j = m + i
		s.add(j - x)
d = {}
for i in b:
	if i in d:
		d[i] = d[i] + 1
	else:
		d[i] = 1
for x in s:
	l = {}
	for i in a:
		u = (i + x) % m
		if u in l:
			l[u] = l[u] + 1
		else:
			l[u] = 1
	f = 0
	s = -1
	for u in l:
		if u in d:
			if d[u] != l[u]:
				f = 1
				break
		else:
			f = 1
			break
	if f == 0:
		s = x
		break
w = str(s)
sys.stdout.write(w)


(n, m) = map(int, input().split())
a = [int(x) for x in input().split()]
b = [int(y) for y in input().split()]
a.sort()
b.sort()
ans = int(1000000000.0 + 1)
for i in range(len(a)):
	x = (b[0] - a[i]) % m
	l = [(x + j) % m for j in a]
	if sorted(l) == b:
		ans = min(x, ans)
print(ans)


from collections import Counter

def check(a, b, m):
	ans = b - a
	if ans >= 0:
		return b - a
	else:
		return m - a + b
(n, m) = [int(i) for i in input().split(' ')]
arr1 = [int(i) for i in input().split(' ')]
arr2 = [int(i) for i in input().split(' ')]
cnt1 = Counter(arr1)
cnt2 = Counter(arr2)
freq_count = Counter(cnt1.values())
mn = min(freq_count.keys(), key=lambda i: freq_count[i])
req1 = None
for i in cnt1:
	if cnt1[i] == mn:
		req1 = i
		break
req2 = [i for i in cnt2 if cnt2[i] == mn]
ansarr = []
for i in req2:
	ansarr.append(check(req1, i, m))
ansarr.sort()
ans = 10 ** 9
for k in ansarr:
	cnt3 = Counter([(arr1[i] + k) % m for i in range(n)])
	if cnt3 == cnt2:
		ans = k
		break
print(ans)


def check(a, b, n, diff):
	flag = list()
	for i in range(n):
		flag.append((a[i] + diff) % m)
	flag.sort()
	for i in range(n):
		if flag[i] != b[i]:
			return False
	return True
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
if n == 1:
	print((b[0] - a[0]) % m)
else:
	mini = 1000000006
	for i in range(n):
		diff = (b[i] - a[0]) % m
		if check(a, b, n, diff):
			if diff < mini:
				mini = diff
	print(mini)


from collections import Counter
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = sorted([list(i) for i in list(Counter(a).items())], key=lambda x: x[0])
d = sorted([list(i) for i in list(Counter(b).items())], key=lambda x: x[0])
n = len(c)
x = 0
for i in range(n):
	p = c.pop(-1)
	dp = d[0][0] + m - p[0]
	x += dp
	c.insert(0, p)
	for j in range(n):
		c[j][0] += dp
		c[j][0] %= m
	if c == d:
		print(x % m)
		break


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for pp in range(t):
		solve(pp)

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def google(p):
	print('Case #' + str(p) + ': ', end='')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def chck(a, b, m, x):
	new = deepcopy(a)
	for i in range(len(a)):
		new[i] += x
		new[i] %= m
	cnt = {}
	for i in range(len(a)):
		if new[i] in cnt:
			cnt[new[i]] += 1
		else:
			cnt[new[i]] = 1
	if cnt == b:
		return True
	return False

def solve(case):
	(n, m) = sep()
	a = lis()
	b = lis()
	acnt = {}
	bcnt = {}
	for i in range(n):
		if a[i] in acnt:
			acnt[a[i]] += 1
		else:
			acnt[a[i]] = 1
		if b[i] in bcnt:
			bcnt[b[i]] += 1
		else:
			bcnt[b[i]] = 1
	mini = 2001
	num = -1
	for i in acnt:
		if acnt[i] < mini:
			mini = acnt[i]
			num = i
	have = []
	for i in bcnt:
		if bcnt[i] == mini:
			have.append(i)
	chcker = []
	for i in range(len(have)):
		if have[i] >= num:
			chcker.append(have[i] - num)
		else:
			chcker.append(m - num + have[i])
	chcker = sorted(chcker)
	for i in chcker:
		if chck(a, bcnt, m, i):
			print(i)
			break
testcase(1)


(n, m) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
b.sort()
x = [0] * n
for i in range(n):
	if a[i] > b[0]:
		x[i] = b[0] - a[i] + m
	else:
		x[i] = b[0] - a[i]
for i in range(n):
	a1 = a.copy()
	a1 = [(a1[j] + x[i]) % m for j in range(n)]
	a1.sort()
	if a1 == b:
		print(x[i])
		break


a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
c = [int(i) for i in input().split()]
n = a[0]
m = a[1]
res = m
b.sort()
c.sort()
if b == c:
	print(0)
else:
	for i in range(n):
		k = int(c[i] - b[0]) % m
		l = int(0)
		for j in range(n):
			if (b[j] + k) % m != c[(i + j) % n]:
				l = 1
				break
		if l == 0:
			res = min(res, k)
	print(res)


def my_function(l1, l2):
	li1 = sorted(l1)
	li2 = sorted(l2)
	if li1 == li2:
		return True
	else:
		return False
(n, mod) = map(int, input().split())
list1 = list(map(int, input().split()))
list2 = list(map(int, input().split()))
possiblesX = set()
for i in range(n):
	possiblesX.add((list2[i] - list1[0]) % mod)
result = 0
for n in possiblesX:
	aux = []
	for k in list1:
		aux.append((k + n) % mod)
	if my_function(aux, list2):
		result = n
print(result)


(n, m) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
t2 = sorted(b)
ans = 10 ** 9
for i in range(n):
	if a[i] <= b[0]:
		curr = b[0] - a[i]
	else:
		curr = m - (a[i] - b[0])
	temp = []
	for j in range(n):
		temp.append((curr + a[j]) % m)
	if sorted(temp) == t2:
		ans = min(ans, curr)
print(ans)


(N, M) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
B.sort()
B0 = B[0]
ans = M
for i in range(N):
	p = (B0 - A[i]) % M
	A_new = [(Aj + p) % M for Aj in A]
	A_new.sort()
	if A_new == B:
		ans = min(ans, p)
print(ans)


(n, m) = map(int, input().split())
a = sorted([int(x) for x in input().split()])
b = sorted([int(x) for x in input().split()])
if a == b:
	print(0)
	exit(0)
diffs = set()
for i in range(n):
	x = b[i] - a[0]
	if x < 0:
		x += m
	diffs.add(x)
for i in diffs:
	c = sorted([(x + i) % m for x in a])
	if c == b:
		print(i)
		exit(0)


R = lambda : map(int, input().split())
s = sorted
(n, m) = R()
(a, b) = (s(R()), s(R()) * 2)
print(min(((b[i] - a[0]) % m for i in range(n) if [(x + b[i] - a[0]) % m for x in a] == b[i:i + n])))


from collections import defaultdict

def solve():
	freq_a = defaultdict(int)
	freq_b = defaultdict(int)
	(n, m) = list(map(int, input().split(' ')))
	arr_a = list(map(int, input().split(' ')))
	arr_b = list(map(int, input().split(' ')))
	for curr in arr_a:
		freq_a[curr] += 1
	for curr in arr_b:
		freq_b[curr] += 1
	amount = defaultdict(int)
	for key_a in freq_a:
		for key_b in freq_b:
			if freq_a[key_a] == freq_b[key_b]:
				delta = key_b - key_a if key_a <= key_b else m + key_b - key_a
				amount[delta] += freq_a[key_a]
	highest = m
	for i in amount:
		if amount[i] == n and i < highest:
			highest = i
	print(highest)
solve()


from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 10 ** 9 + 7

def factors(n):
	return sorted(list(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split(' ')]

def st():
	return input().rstrip('\n')

def val():
	return int(input())

def li2():
	return [i for i in input().rstrip('\n').split(' ')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
(n, m) = li()
a = li()
b = li()
ans = float('inf')
cnt = Counter(b)
if sorted(a) == sorted(b):
	print(0)
	exit()
for i in range(n):
	if b[i] > a[0]:
		temp = b[i] - a[0]
	else:
		temp = m - a[0] + b[i]
	cnt2 = Counter()
	for j in range(n):
		cnt2[(a[j] + temp) % m] += 1
	if cnt == cnt2:
		ans = min(ans, temp)
print(ans)


(num_de_elem, divisor) = map(int, input().split())
sequencia1 = list(map(int, input().split()))
sequencia2 = list(map(int, input().split()))
sequencia2.sort()
aux1 = []
for i in range(num_de_elem):
	aux1.append((sequencia2[0] - sequencia1[i]) % divisor)
aux1 = list(set(aux1))
aux2 = []
while aux2 != sequencia2:
	for indice in aux1:
		aux2 = []
		for j in range(num_de_elem):
			aux2.append((sequencia1[j] + indice) % divisor)
		aux2.sort()
		if aux2 == sequencia2:
			break
print(indice)


import sys
from collections import Counter
(n, m) = map(int, input().split())
arr1 = sorted(list(map(int, input().split())))
arr2 = sorted(list(map(int, input().split())))
ans = 99999999999999
for i in range(n):
	t = arr2[i] - arr1[0]
	if t > 0:
		x = t % m
	else:
		x = (m + t) % m
	temp = []
	for j in range(n):
		temp.append((arr1[j] + x) % m)
	temp.sort()
	if temp == arr2:
		ans = min(ans, x)
print(ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a = sorted(a)
b = sorted(b)
if a == b:
	print(0)
else:
	diff = 0
	al = []
	for i in range(n):
		if b[i] > a[0]:
			al.append(b[i] - a[0])
		else:
			al.append(m + b[i] - a[0])
	goal = al.copy()
	goal = sorted(goal)
	for i in goal:
		aa = a.copy()
		for j in range(n):
			aa[j] = (aa[j] + i) % m
		aa = sorted(aa)
		if aa == b:
			print(i)
			break


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
count = 0
while a != b:
	d = b[-1] - a[-1]
	if d == 0:
		d = 1
	elif d < 0:
		d = m - a[-1]
	count += d
	a = list(map(lambda k: (k + d) % m, a))
	a.sort()
print(count)


from collections import Counter
(n, m) = list(map(int, input().split()))
a = Counter(list(map(int, input().split())))
b = Counter(list(map(int, input().split())))
dct = {}
variants = Counter()
for i in a:
	if a[i] not in dct:
		dct[a[i]] = []
	dct[a[i]].append(i)
for i in b:
	count = b[i]
	for j in dct[count]:
		if i - j >= 0:
			variants[i - j] += 1
		else:
			variants[i - j + m] += 1
mx = -float('inf')
ans = 0
for i in variants:
	if variants[i] > mx or (variants[i] == mx and i < ans):
		ans = i
		mx = variants[i]
print(ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
ans = m
for i in range(n):
	s = (b[i] + m - a[0]) % m
	ok = 1
	for j in range(n):
		if (a[j] + s) % m != b[(i + j) % n]:
			ok = 0
			break
	if ok:
		ans = min(ans, s)
print(ans)


import collections
(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
ans = float('inf')
for i in range(n):
	x = (b[0] - a[i]) % m
	ax = []
	for j in range(n):
		ax.append((a[j] + x) % m)
	if b == sorted(ax):
		ans = min(ans, x)
print(ans)


(n, k) = map(int, input().split())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
l1.sort()
l2.sort()

def rev(a, n):
	for i in range(n - 1):
		(a[i], a[i + 1]) = (a[i + 1], a[i])
	return a
fg = 0
m = k - 1
for _ in range(n):
	fg = 0
	temp = (l2[0] - l1[0]) % k
	for i in range(1, n):
		if temp != (l2[i] - l1[i]) % k:
			fg = 1
			break
	if fg == 0 and m > temp:
		m = temp
	l2 = rev(l2, n)
print(m)


out = 0

def swap():
	global out
	if a[-1] > mb:
		t = m - a[-1] + mb
	else:
		t = mb - a[-1]
	out += t
	for i in range(n):
		a[i] += t
	a.insert(0, mb)
	del a[-1]
(n, m) = map(int, input().split())
a = sorted(map(int, input().split()))
b = sorted(map(int, input().split()))
mb = min(b)
while a != b:
	swap()
print(out)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
ans = m
for i in range(n):
	x = (b[i] - a[0] + m) % m
	for j in range(n):
		if (a[j] + x) % m != b[(i + j) % n]:
			break
	else:
		ans = min(ans, x)
print(ans)


(n, m) = map(int, input().split(' '))
a = list(map(int, input().split(' ')))
b = list(map(int, input().split(' ')))
b.sort()
ans = m
for i in a:
	x = (b[0] - i) % m
	s = [(j + x) % m for j in a]
	s.sort()
	if s == b:
		ans = min(ans, x)
print(ans)


import sys
from collections import defaultdict
(n, m) = map(int, sys.stdin.readline().split())
a = list(map(int, sys.stdin.readline().split()))
b = list(map(int, sys.stdin.readline().split()))
a.sort()
b.sort()
(dica, dicb) = (defaultdict(int), defaultdict(int))
for i in range(n):
	dica[a[i]] += 1
	dicb[b[i]] += 1
ans = float('inf')
for i in range(n):
	(counta, countb) = (dica[a[i]], dicb[b[0]])
	if counta == countb:
		z = a[i] % m
		if z > b[0]:
			x = m + b[0] - z
		else:
			x = b[0] - z
		(k, flag) = (i, True)
		for j in range(n):
			if (a[k] + x) % m != b[j]:
				flag = False
				break
			else:
				k += 1
				if k >= n:
					k = 0
		if flag:
			ans = min(ans, x)
		i += counta
	else:
		i += counta
print(ans)


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
for j in range(n):
	c = b[j:] + b[:j]
	diff = []
	for i in range(n):
		diff.append((c[i] - a[i]) % m)
	if diff.count(diff[0]) == n:
		print(diff[0] % m)
		break


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
pos = [(b[i] - a[0]) % m for i in range(n)]
for x in pos:
	new = [(a[i] + x) % m for i in range(n)]
	new.sort()
	if new == b:
		print(x)
		break


import sys
(n, m) = map(int, sys.stdin.readline().split())
(*a,) = map(int, sys.stdin.readline().split())
(*b,) = map(int, sys.stdin.readline().split())

def main():
	a.sort()
	b.sort()
	ma = b[-1]
	cand = set()
	for i in range(n):
		cand.add((ma - a[i]) % m)
	for c in sorted(cand):
		a2 = [(x + c) % m for x in a]
		a2.sort()
		if a2 == b:
			return c
ans = main()
print(ans)


def main():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	arr = []
	for i in range(n):
		temp = b[0] - a[i]
		if temp < 0:
			temp += m
		arr.append(temp)
	arr.sort()
	b.sort()
	for i in range(n):
		arr2 = []
		flag = True
		for j in range(n):
			arr2.append((a[j] + arr[i]) % m)
		arr2.sort()
		for k in range(n):
			if b[k] != arr2[k]:
				flag = False
				break
		if flag == True:
			print(arr[i])
			return
	return
main()


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
x = 0
a1 = {}
b1 = {}
(l, p) = ([], [])
for i in set(a):
	y = a.count(i)
	a1[i] = y
	l.append([y, i])
for i in set(b):
	y = b.count(i)
	b1[i] = y
	p.append([y, i])
l.sort()
p.sort()
h = []
d = []
if a1 != b1:
	j = len(l) - 1
	k = l[j][0]
	for i in range(j, -1, -1):
		if p[i][0] == k:
			d.append(p[i][1])
			h.append(l[i][1])
		else:
			break
	h.sort()
	d.sort()
	x = m + 1
	for i in range(len(h)):
		k = (d[0] - h[i]) % m
		if sorted([(j + k) % m for j in h]) == d:
			x = min(x, k)
print(x)


(n, m) = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
a = sorted(a)
b = sorted(b)
x = 10000000000
for i in range(n):
	p = (b[0] - a[i]) % m
	a_new = [(aj + p) % m for aj in a]
	a_new = sorted(a_new)
	if a_new == b:
		x = min(p, x)
print(x)


import sys

def find_min(n, m, a, b):
	best = m
	for v in b:
		d = (v - a[0] + m) % m
		arr = [(x + d) % m for x in a]
		if sorted(arr) == sorted(b):
			best = min(best, d)
	return best

def solve(io):
	N = io.read_int()
	M = io.read_int()
	A = io.read_int_array(N)
	B = io.read_int_array(N)
	x = find_min(N, M, A, B)
	io.println(x)

class IO:
	in_stream = None
	out_stream = None
	raw = ''
	buf = []
	pos = 0

	def __init__(self, input_stream, output_stream):
		self.in_stream = input_stream
		self.out_stream = output_stream

	def read_to_buffer(self):
		self.raw = self.in_stream.readline().rstrip('\n')
		self.buf = self.raw.split()
		self.pos = 0

	def read_string(self):
		while self.pos == len(self.buf):
			self.read_to_buffer()
		ans = self.buf[self.pos]
		self.pos += 1
		return ans

	def read_int(self):
		return int(self.read_string())

	def read_float(self):
		return float(self.read_string())

	def read_string_array(self, N, offset=0):
		arr = [None] * offset
		for _ in range(0, N):
			arr.append(self.read_string())
		return arr

	def read_int_array(self, N, offset=0):
		arr = [None] * offset
		for _ in range(0, N):
			arr.append(self.read_int())
		return arr

	def read_float_array(self, N, offset=0):
		arr = [None] * offset
		for _ in range(0, N):
			arr.append(self.read_float())
		return arr

	def read_line(self):
		while self.pos == len(self.buf):
			self.read_to_buffer()
		if self.pos > 0:
			raise ValueError('Cannot call read_line in the middle of a line.')
		self.pos = len(self.buf)
		return self.raw

	def print(self, *args):
		self.out_stream.write(' '.join([str(x) for x in args]))

	def println(self, *args):
		self.print(*args)
		self.print('\n')

	def println_array(self, arr, sep=' '):
		self.println(sep.join((str(x) for x in arr)))

	def flush_output(self):
		self.out_stream.flush()
pythonIO = IO(sys.stdin, sys.stdout)
solve(pythonIO)
pythonIO.flush_output()


entrada = list(input().split())
mod = int(entrada[1])
cont1 = list(input().split())
cont2 = sorted(map(int, input().split()))
valor = 0
arr = []
for i in range(int(entrada[0])):
	valor = (cont2[0] - int(cont1[i])) % mod
	arr.append(valor)
for i in set(arr):
	arr2 = []
	for j in range(int(entrada[0])):
		arr2.append((int(cont1[j]) + i) % mod)
	arr2.sort()
	if arr2 == cont2:
		print(i)
		break


(A, m) = map(int, input().split(' '))
c = list(map(int, input().split(' ')))
d = list(map(int, input().split(' ')))
C = sorted(c)
D = sorted(d)
if C == D:
	print(0)
else:
	li = []
	l = []
	x = min(D)
	E = list(set(C))
	for i in E:
		F = C.copy()
		if i < m:
			if x < i:
				z = m - i + x
			else:
				z = x - i
		elif i > m:
			for j in range(m, 1000000001, m):
				if j > i:
					z = j - i + x
					break
		if z not in li:
			final = list(map(lambda x: (x + z) % m, F))
			li.append(z)
			if sorted(final) == D:
				l.append(z)
	print(min(l))


(n, m) = map(int, input().split())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
b = sorted(b)
c = []
for i in range(n):
	c.append((b[i] - a[0]) % m)
sch1 = 0
while sch1 < n:
	qwe = 0
	d = []
	for i in range(n):
		d.append((a[i] + c[sch1]) % m)
	d = sorted(d)
	sch2 = 0
	while sch2 < n:
		if d[sch2] != b[sch2]:
			break
		else:
			sch2 += 1
	if sch2 == n:
		print(c[sch1])
		break
	else:
		sch1 += 1


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a = [u % m for u in a]
b = [u % m for u in b]
a.sort()
b.sort()
possible = set(sorted([(b[0] - u + m) % m for u in a]))
for x in possible:
	array = [(u + x) % m for u in a]
	if sorted(array) == b:
		print(x)
		break


INF = 10 ** 10

def main():
	(n, m) = get_list()
	a = get_list()
	b = get_list()
	cnta = Counter(a)
	cntb = Counter(b)
	keys = list(sorted(cntb.keys()))

	def chk(x):
		for i in keys:
			try:
				if cntb[i] != cnta[(i - x) % m]:
					return False
			except:
				return False
		return True
	key1 = list(sorted(cnta.keys()))[0]
	res = INF
	for ele in keys:
		if cnta[key1] == cntb[ele] and chk(ele - key1):
			res = min(res, (ele - key1) % m)
	print(res)
import sys
from collections import defaultdict, Counter
from bisect import bisect_left, bisect_right
import math
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
out = []
get_int = lambda : int(input())
get_list = lambda : list(map(int, input().split()))
main()
print(*out, sep='\n')


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

def inputlist():
	return list(map(int, input().split()))

def inputstring():
	return [x for x in input()]

def inputstringnum():
	return [ord(x) - ord('a') for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
(n, m) = inputnums()
a = inputlist()
b = inputlist()
d = b
d.sort()
ans = m
c = [0] * n
for i in range(n):
	x = (b[i] - a[0]) % m
	for j in range(n):
		c[j] = (a[j] + x) % m
	c.sort()
	if c == d:
		ans = min(ans, x)
print(ans)


from sys import stdin

def get_x(first, second):
	if first <= second:
		return second - first
	else:
		return m - first + second

def check(first, second):
	x = get_x(first, second)
	aux = arr[:]
	for i in range(n):
		aux[i] += x
		aux[i] %= m
	aux.sort()
	return aux == barr
(n, m) = list(map(int, stdin.readline().split()))
arr = list(map(int, stdin.readline().split()))
barr = list(map(int, stdin.readline().split()))
barr.sort()
ans = float('inf')
for i in range(n):
	if check(arr[i], barr[0]):
		ans = min(ans, get_x(arr[i], barr[0]))
print(ans)


(n, m) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
A.sort()
B.sort()
ans = []
for num in range(n):
	temp = A[0] - B[0 - num] if A[0] - B[0 - num] < 0 else A[0] - B[0 - num] - m
	ans.append(temp)
	for i in range(n):
		if temp != (A[i] - B[i - num] if A[i] - B[i - num] < 0 else A[i] - B[i - num] - m):
			ans.pop(-1)
			break
ans.sort()
print(-ans[-1] if ans[-1] != -m else 0)


from math import ceil
from math import floor
from math import sqrt
from math import log
prime = pow(10, 9) + 7

def mod_expo(n, p, m):
	result = 1
	while p != 0:
		if p % 2 == 1:
			result = result * n % m
		p //= 2
		n = n * n % m
	return result

def are_same(arr, b):
	a1 = list()
	b1 = list()
	a1 = arr.copy()
	b1 = b.copy()
	a1.sort()
	b1.sort()
	return a1 == b1

def find_xmin(n, m, arr, b):
	mn = m
	if are_same(arr, b):
		return 0
	for i in range(n):
		x = (b[0] - arr[i]) % m
		if x < 0:
			x += m
		c = []
		for j in range(n):
			c.append((arr[j] + x) % m)
		if are_same(c, b):
			mn = min(mn, x)
	return mn
t = 1
while t:
	t = t - 1
	count = 0
	(n, m) = map(int, input().split())
	arr = list(map(int, input().strip().split()))[:n]
	b = list(map(int, input().strip().split()))[:n]
	print(find_xmin(n, m, arr, b))


from collections import Counter
(_, m) = map(int, input().split())
a_count = sorted(map(int, input().split()))
b_count = sorted(map(int, input().split()))
b = b_count[0]
c = 0
for val in a_count:
	if b >= val:
		c = b - val
	else:
		c = m - val + b
	new_arr = sorted([(val + c) % m for val in a_count])
	if new_arr == b_count:
		break
print(c)


(n, m) = map(int, input().split())
a = sorted(list(map(int, input().split())))
b = sorted(list(map(int, input().split())))
ans = []
for i in range(n):
	d = (b[0] - a[i]) % m
	temp = []
	for j in range(n):
		temp.append((a[j] + d) % m)
	temp.sort()
	if temp == b:
		ans.append(d)
print(min(ans))


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
s = set()
for i in range(1):
	for j in range(n):
		x = b[j] - a[0]
		if x < 0:
			x += m
		s.add(x)
for i in sorted(list(s)):
	c = []
	for j in a:
		c.append((j + i) % m)
	c.sort()
	if c == b:
		print(i)
		exit()


(n, m) = map(int, input().split())
a = map(int, input().split())
a = list(a)
a.sort()
b = map(int, input().split())
b = list(b)
b.sort()
diffa = [0] * (n - 1)
diffb = [0] * (n - 1)
for i in range(n - 1):
	diffa[i] = a[i + 1] - a[i]
	diffb[i] = b[i + 1] - b[i]
q = a[n - 1] - a[0]
q = m - q
q = q % m
diffa.append(q)
arr = []
if diffa[0:n - 1] == diffb:
	x = b[0] - a[0]
	if x < 0:
		x = x + m
	arr.append(x)
for i in range(n - 1, 0, -1):
	c1 = i
	diff = []
	for i1 in range(n - 1):
		diff.append(diffa[c1])
		c1 = c1 + 1
		if c1 > n - 1:
			c1 = 0
	if diff == diffb:
		x = b[0] - a[i]
		if x < 0:
			x = x + m
		arr.append(x)
print(min(arr))


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
l = []
pos = [(b[i] - a[0]) % m for i in range(n)]
for i in pos:
	s = [(j + i) % m for j in a]
	s.sort()
	if s == b:
		l.append(i)
print(min(l))


(n, m) = list(map(int, input().split()))
arr = list(map(int, input().split()))
brr = list(map(int, input().split()))
arr.sort()
brr.sort()
ans = []
for i in range(n):
	cur = (brr[0] - arr[i]) % m
	temp = []
	for j in range(n):
		temp.append((arr[j] + cur) % m)
	temp.sort()
	if temp == brr:
		ans.append(cur)
print(min(ans))


from os import path
import sys
from heapq import heappush, heappop, heapify
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input().rstrip()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def b(i):
	return ord(i) - ord('a')
file = 1

def solve():
	(n, m) = mi()
	a = li()
	b = li()
	s = set()
	freq_a = dd(int)
	freq_b = dd(int)
	for i in a:
		freq_a[i] += 1
	for i in b:
		freq_b[i] += 1
	f = 0
	for i in freq_b.keys():
		s_i = set()
		for j in freq_a.keys():
			if freq_a[j] == freq_b[i]:
				if i >= j:
					x = i - j
				else:
					x = m - j + i
				s_i.add(x)
		if f == 0:
			s = s_i
			f = 1
			continue
		s2 = s - s_i
		s = s - s2
	s = list(s)
	print(min(s))
if file:
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	else:
		input = sys.stdin.readline
solve()


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
x = []
for i in range(n):
	x.append((b[0] - a[i] + m) % m)
ans = 10000000000.0
for i in x:
	newA = []
	for j in range(n):
		newA += [(a[j] + i) % m]
	newA.sort()
	if newA == b:
		ans = min(ans, i)
print(ans)


(n, m) = tuple(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
x = []
for i in range(n):
	x.append((b[0] - a[i]) % m)
x = list(set(x))
for i in range(len(x)):
	k = []
	for j in range(n):
		k.append((a[j] + x[i]) % m)
	k.sort()
	if k == b:
		print(x[i])
		break


from sys import stdin
inp = lambda : stdin.readline().strip()
(n, m) = [int(x) for x in inp().split()]
a = [int(x) for x in inp().split()]
b = [int(x) for x in inp().split()]
a.sort()
b.sort()
ans = 10 ** 9 + 1
for i in range(n):
	count = -1
	for j in range(n):
		if count == -1:
			count = (b[j] - a[(j + i) % n]) % m
		elif (b[j] - a[(j + i) % n]) % m != count:
			break
	else:
		ans = min(ans, count)
print(ans)


import sys

def rint():
	return map(int, sys.stdin.readline().split())

def input():
	return sys.stdin.readline().rstrip('\n')

def oint():
	return int(input())
(n, m) = rint()
a = list(rint())
b = list(rint())
a.sort()
b.sort()
min_ans = 10 ** 9
for i in range(n):
	prev = 0
	diff = 0
	for j in range(n):
		bb = b[(i + j) % n]
		aa = a[j]
		diff = ((bb + m) % m - aa) % m
		if j == 0:
			prev = diff
			continue
		elif prev != diff:
			break
	else:
		min_ans = min(min_ans, diff % m)
print(min_ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
p = [(bi - a[0]) % m for bi in b]
p.sort()
for i in p:
	s = [(ai + i) % m for ai in a]
	s.sort()
	if s == b:
		print(i)
		break


(n, m) = map(int, input().split())
a = sorted(list(map(int, input().split())))
b = sorted(list(map(int, input().split())))
r = m
for i in range(n):
	s = []
	x = (b[0] - a[i]) % m
	for j in range(n):
		s.append((a[j] + x) % m)
	s.sort()
	if s == b:
		r = min(r, x)
print(r)


def inp():
	return map(int, input().split())
(n, m) = inp()
b = list(inp())
a = list(inp())
a.sort()
b.sort()
b += b
for i in range(n):
	k = a[0] - b[i]
	res = True
	for j in range(i + 1, i + n):
		x = a[j - i] - b[j]
		y = a[j - i] - b[j] + m
		z = a[j - i] - b[j] - m
		if x != k and y != k and (z != k):
			res = False
			break
	if res:
		print(k if k >= 0 else m + k)
		break


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
a_dif = [(a[(i + 1) % n] - a[i]) % m for i in range(n)]
b_dif = [(b[(i + 1) % n] - b[i]) % m for i in range(n)]
b_dif *= 2
pos_index = list()
for (i, e) in enumerate(b_dif):
	if i >= n:
		break
	if b_dif[i:i + n] == a_dif:
		pos_index.append(i)
print(min([(b[i] - a[0]) % m for i in pos_index]))


(n, m) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
from collections import Counter
CA = Counter(A)
CB = Counter(B)
X = []
for (a, cnta) in CA.items():
	S = set()
	for (b, cntb) in CB.items():
		if cnta == cntb:
			if b >= a:
				S.add(b - a)
			else:
				S.add(m + b - a)
	X.append(S)
ans = m + 1
for i in X[0]:
	for j in range(len(X)):
		S = X[j]
		if i not in S:
			break
	else:
		ans = min(i, ans)
print(ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
ans = m
for num in a:
	x = (b[0] - num) % m
	c = [(elem + x) % m for elem in a]
	c.sort()
	if b == c:
		ans = min(x, ans)
print(ans)


import sys
import math

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def MI():
	return map(int, sys.stdin.readline().split())

def SI():
	return sys.stdin.readline().strip()
(n, m) = MI()
a = LI()
b = sorted(LI())
if a == b:
	print(0)
else:
	c = [(b[i] - a[0]) % m for i in range(n)]
	for i in sorted(c):
		s = [(a[j] + i) % m for j in range(n)]
		if sorted(s) == b:
			print(i)
			break


(n, m) = map(int, input().split())
arr = list(map(int, input().split()))
arr1 = list(map(int, input().split()))
xs = set()
for i in range(n):
	if arr[0] > arr1[i]:
		xs.add(m - abs(arr[0] - arr1[i]))
	else:
		xs.add(arr1[i] - arr[0])
arr.sort()
arr1.sort()
if arr == arr1:
	print(0)
else:
	for i in xs:
		n_ = []
		for j in range(n):
			n_.append((arr[j] + i) % m)
		n_.sort()
		if n_ == arr1:
			print(i)
			break


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

def fuck(x):
	c = []
	for i in range(n):
		c.append((a[i] + x) % m)
	c.sort()
	for i in range(n):
		if b[i] != c[i]:
			return 0
	return 1
ans = 1061109567
for i in range(n):
	s = ((b[0] - a[i]) % m + m) % m
	if fuck(s) == 1:
		ans = min(ans, s)
print(ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = sorted(map(int, input().split()))
s1 = set()
for j in range(n):
	if a[0] <= b[j]:
		s1.add(b[j] - a[0])
	else:
		s1.add(m - a[0] + b[j])
s1 = sorted(s1)
tmp = [0] * n
for i in s1:
	for j in range(n):
		tmp[j] = (a[j] + i) % m
	if sorted(tmp) == b:
		print(i)
		break


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
ans = []
for i in range(n):
	if b[-1] < a[i]:
		ans.append(b[-1] - a[i] + m)
	else:
		ans.append(b[-1] - a[i])
ans = list(set(ans))
ans.sort()
for i in ans:
	temp = []
	for j in range(n):
		temp.append((a[j] + i) % m)
	if sorted(temp) == b:
		print(i)
		return
print(1 / 0)


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = sorted(list(map(int, input().split())))
min_rez = m + 1
for i in range(n):
	x = (b[0] - a[i]) % m
	a_prim = sorted([(int(element) + x) % m for element in a])
	if a_prim == b:
		min_rez = min(min_rez, x)
print(min_rez)


import sys
[n, m] = [int(i) for i in sys.stdin.readline().split()]
a = [int(j) for j in sys.stdin.readline().split()]
b = [int(k) for k in sys.stdin.readline().split()]
ans = -2
for i in range(n):
	d = {}
	for h in range(n):
		if b[h] in d:
			d[b[h]] += 1
		else:
			d[b[h]] = 1
	x = (b[i] - a[0]) % m
	done = 1
	for j in range(n):
		val = (a[j] + x) % m
		if val in d and d[val] > 0:
			d[val] -= 1
		else:
			done = 0
			break
	if done == 1:
		if ans == -2:
			ans = x
		else:
			ans = min(ans, x)
print(ans)


from sys import stdin, stdout

def solve(a, b, m, n):
	out = stdout.write
	b.sort()
	t = [0] * n
	ans = m
	k = a[:]
	for i in k:
		x = (b[0] - i + m) % m
		for j in range(n):
			t[j] = (x + a[j]) % m
		t.sort()
		ch = True
		for j in range(n):
			if not t[j] == b[j]:
				ch = False
				break
		if ch:
			ans = min(ans, x)
	out(str(ans) + '\n')

def main():
	inp = stdin.readline
	(n, m) = map(int, inp().split())
	a = list(map(int, inp().split()))
	b = list(map(int, inp().split()))
	solve(a, b, m, n)
main()


(n, m) = map(int, input().split())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
(s1, s2, flag, ans) = (set(), [], 0, [])
for i in b:
	s2.append(set())
	for j in a:
		if i >= j:
			s1.add(i - j)
			s2[len(s2) - 1].add(i - j)
		else:
			s1.add(i + m - j)
			s2[len(s2) - 1].add(i + m - j)
for i in s1:
	for j in s2:
		if i in j:
			flag = 1
			continue
		else:
			flag = 0
			break
	if flag == 1:
		ans.append(i)
b.sort()
realans = []
for i in ans:
	new = a[:]
	for j in range(len(new)):
		new[j] = (new[j] + i) % m
	new.sort()
	if new == b:
		realans.append(i)
print(min(realans))


from math import inf

def solve(n, m, a, b):
	a.sort()
	b.sort()
	if a == b:
		return 0
	k = b[0]
	mini = inf
	for i in a:
		x = (k - i) % m
		c = sorted([(i + x) % m for i in a])
		if c == b:
			mini = min(x, mini)
	return mini

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


from sys import stdin, stdout
from math import sqrt
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
s = []
for i in range(n):
	if a[0] <= b[i]:
		s.append(b[i] - a[0])
	else:
		s.append(m + b[i] - a[0])
ans = []
for i in range(n):
	temp = []
	for j in range(n):
		temp.append((a[j] + s[i]) % m)
	temp.sort()
	if temp == b:
		ans.append(s[i])
print(min(ans))


import sys

class BModuloEquality:

	def solve(self):
		from collections import defaultdict
		(n, m) = [int(_) for _ in input().split()]
		a = [int(_) for _ in input().split()]
		b = [int(_) for _ in input().split()]
		cnt_b = defaultdict(int)
		for x in b:
			cnt_b[x] += 1
		cnt_a = defaultdict(int)
		for x in a:
			cnt_a[x] += 1
		b_list = [[cnt_b[x], x] for x in cnt_b]
		a_list = [[cnt_a[x], x] for x in cnt_a]
		cands = []
		for i in range(len(b_list)):
			if b_list[i][0] == a_list[0][0]:
				cands.append((b_list[i][1] - a_list[0][1]) % m)
		cands.sort()
		for x in cands:
			if sorted([(i + x) % m for i in a]) == sorted(b):
				print(x)
				return
solver = BModuloEquality()
input = sys.stdin.readline
solver.solve()


(n, m) = map(int, input().split())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
a.sort()
b.sort()
list_of_lists = [[i for i in a[start:] + a[0:start]] for start in range(n)]
min_candidate = float('inf')
for l in list_of_lists:
	if l[0] < b[0]:
		candidate = m - b[0]
	elif l[0] == b[0]:
		candidate = 0
	else:
		candidate = m - l[0] + b[0]
	counter = 0
	for (ind, b_i) in enumerate(b):
		if (l[ind] + candidate) % m == b_i:
			counter += 1
	if counter == n:
		min_candidate = candidate if candidate < min_candidate else min_candidate
print(min_candidate)


(n, m) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
a = sorted(a)
b = sorted(b)
moves = set()
bb = list(set(b))
aa = list(set(a))
for ii in range(len(aa)):
	for x in [(bb[i] - aa[ii]) % m for i in range(len(bb))]:
		moves.add(x)
pastmv = 0
ans = m + 5
b = b
for mvv in moves:
	mv = pastmv + mvv
	aa = sorted([(x + mv) % m for x in a])
	fl = aa == b
	if fl:
		ans = min(ans, mv)
		break
if ans != m + 5:
	print(ans)
else:
	raise NotImplemented()


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a_el_count = {}
b_el_count = {}
for el in a:
	if el in a_el_count:
		a_el_count[el] += 1
	else:
		a_el_count[el] = 1
for el in b:
	if el in b_el_count:
		b_el_count[el] += 1
	else:
		b_el_count[el] = 1
a_count_el = {}
b_count_el = {}
a_unique = list(set(a))
len_a_unique = len(a_unique)
b_unique = list(set(b))
len_b_unique = len(b_unique)
for el in a_unique:
	if a_el_count[el] in a_count_el:
		a_count_el[a_el_count[el]].add(el)
	else:
		a_count_el[a_el_count[el]] = {el}
for el in b_unique:
	if b_el_count[el] in b_count_el:
		b_count_el[b_el_count[el]].add(el)
	else:
		b_count_el[b_el_count[el]] = {el}
ans_set = set([(item + m - a_unique[0]) % m for item in b_count_el[a_el_count[a_unique[0]]]])
for a_el in a_unique:
	ans_set = ans_set.intersection(set([(item - a_el + m) % m for item in b_count_el[a_el_count[a_el]]]))
print(min(ans_set))


inp = input().split()
n = int(inp[0])
m = int(inp[1])
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()

def f(a, b, m):
	if (b - a) % m < 0:
		return (b - a) % m + m
	else:
		return (b - a) % m
ans = -1
for i in range(n):
	bisa = False
	cnt = 0
	tmp = f(a[0], b[i], m)
	for j in range(n):
		if f(a[j], b[(i + j) % n], m) != tmp:
			break
		cnt += 1
	if cnt == n:
		if not bisa:
			bisa = True
			ans = tmp
		else:
			ans = min(ans, tmp)
print(ans)


import sys
import math
from collections import defaultdict, Counter
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for i in range(1):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	a.sort()
	b.sort()
	ans = m
	for j in range(n):
		start = 0
		for k in range(j, n):
			if k == j:
				if b[k] < a[start]:
					cur = m + b[k] - a[start]
				else:
					cur = b[k] - a[start]
			else:
				if b[k] < a[start]:
					cur1 = m + b[k] - a[start]
				else:
					cur1 = b[k] - a[start]
				if cur1 != cur:
					break
			start += 1
		else:
			for k in range(j):
				if b[k] < a[start]:
					cur1 = m + b[k] - a[start]
				else:
					cur1 = b[k] - a[start]
				if cur1 != cur:
					break
				start += 1
			else:
				ans = min(cur % m, ans)
	print(ans)


(a, b) = input().split(' ')
a = int(a)
b = int(b)
c = list(map(int, input().split()))
d = list(map(int, input().split()))
c.sort()
d.sort()
l = []
for i in range(0, a):
	ans = -1
	t = True
	for j in range(0, a):
		cur = (d[(i + j) % a] - c[j]) % b
		if ans == -1:
			ans = cur
		elif ans != cur:
			t = False
			break
	if t == True:
		l.append(ans)
print(min(l))


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = sorted(list(map(int, input().split())))
diffs = set()
for i in range(n):
	diffs.add((b[0] - a[i]) % m)
diffs = list(diffs)
for d in diffs:
	aux = []
	for ea in a:
		aux.append((ea + d) % m)
	if sorted(aux) == b:
		print(d)
		break


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
dicb = {}
for i in range(n):
	if b[i] not in dicb:
		dicb[b[i]] = 1
	else:
		dicb[b[i]] += 1
ans = 10 ** 10
for i in range(n):
	value = (b[i] - a[0] + m) % m
	dica = {}
	for j in range(n):
		c = (a[j] + value) % m
		if c not in dica:
			dica[c] = 1
		else:
			dica[c] += 1
	flag = 1
	for i in dicb.keys():
		if i not in dica:
			flag = 0
			break
		elif dicb[i] != dica[i]:
			flag = 0
			break
	if flag == 1:
		ans = min(ans, value)
print(ans)


(n, m) = map(int, input().split())
a = [int(k) for k in input().split()]
b = [int(k) for k in input().split()]
a.sort()
b.sort()
ans = 10 ** 9
for i in range(n):
	x = (b[0] - a[i]) % m
	l = []
	for j in range(n):
		l.append((x + a[j]) % m)
	if sorted(l) == b:
		ans = min(ans, x)
print(ans)


import sys
input = lambda : sys.stdin.readline().strip('\r\n')
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
maxi = float('inf')
for i in range(n):
	x = (b[0] % m - a[i] % m) % m
	c = [0] * n
	for i in range(n):
		c[i] = (a[i] + x) % m
	c.sort()
	flag = 1
	for k in range(n):
		if c[k] != b[k]:
			flag = 0
	if flag:
		if x < maxi:
			maxi = x
print(maxi)


(_, m) = [int(n) for n in input().split()]
a = [int(n) for n in input().split()]
b = [int(n) for n in input().split()]
candidates = []
for (i, sumed) in enumerate(b):
	if a[0] <= sumed:
		candidates.append(sumed - a[0])
	else:
		candidates.append(m - a[0] + sumed)
candidates = sorted(candidates)
for potential in candidates:
	new_a = sorted([(n + potential) % m for n in a])
	if new_a == sorted(b):
		print(potential)
		break


(n, m) = map(int, input().split())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
a.sort()
b.sort()
ans = 10 ** 12
for t in range(n):
	k = (b[0] - a[t - 1]) % m
	bo = True
	for i in range(t - 1, n + t - 1):
		if (b[i - t + 1] - a[i % n]) % m != k:
			bo = False
			break
	if bo:
		ans = min(ans, k)
print(ans)


import sys
input = sys.stdin.readline

def chec(arr, brr, mod):
	if brr[0] >= arr[0]:
		add = brr[0] - arr[0]
	else:
		add = brr[0] + mod - arr[0]
	for i in range(len(arr)):
		if (arr[i] + add) % mod != brr[i]:
			return -1
	return add
(n, mod) = map(int, input().split())
arr = list(map(int, input().split()))
brr = list(map(int, input().split()))
arr.sort()
brr.sort()
flag = chec(arr, brr, mod)
while flag == -1:
	arr = [arr[n - 1]] + arr[0:n - 1]
	flag = chec(arr, brr, mod)
print(flag)


from collections import Counter
(n, m) = map(int, input().split())
a = list(Counter(map(int, input().split())).items())
b = list(Counter(map(int, input().split())).items())
assert len(a) == len(b)
k = len(a)
a.sort()
b.sort()
ans = m
for i in range(k):
	tmp = (b[i][0] - a[0][0]) % m
	for j in range(k):
		if b[(j + i) % k][1] != a[j][1] or (b[(j + i) % k][0] - a[j][0]) % m != tmp:
			break
	else:
		ans = min((b[i][0] - a[0][0]) % m, ans)
print(ans)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
ans = []
for i in range(n):
	if a[i] <= b[0]:
		x = b[0] - a[i]
	else:
		x = k - a[i] + b[0]
	d = []
	for i in range(n):
		d.append((a[i] + x) % k)
	d.sort()
	if d == b:
		ans.append(x)
print(min(ans))


from collections import Counter
(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(len(b)):
	b[i] = b[i] % m
for i in range(len(a)):
	a[i] = a[i] % m
b = sorted(b)
a = sorted(a)
counterb = Counter(b)
temp = a[:]
for i in range(len(temp)):
	temp[i] = (m + b[0] - a[i]) % m
temp = list(set(sorted(temp)))
for x in temp:
	newa = [(i + x) % m for i in a]
	countera = Counter(newa)
	if countera == counterb:
		print(x)
		break


import sys
from sys import stdin, stdout
import bisect
import math
import heapq

def modinv(n, p):
	return pow(n, p - 2, p)

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())
import math

def Divisors(n):
	l = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l

def main():
	(n, m) = cin()
	a = ain()
	b = ain()
	a.sort()
	b.sort()
	ans = 1000000000
	for i in range(n):
		p = (b[0] - a[0] + m) % m
		f = 1
		for j in range(n):
			if (a[j] + p) % m != b[j]:
				f = 0
		if f == 1:
			ans = min(p, ans)
		c = a[0]
		for j in range(n - 1):
			a[j] = a[j + 1]
		a[n - 1] = c
	print(ans)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def readnumbers(zero=0):
	conv = ord if py2 else lambda x: x
	A = []
	numb = zero
	sign = 1
	i = 0
	s = sys.stdin.buffer.read()
	try:
		while True:
			if s[i] >= b'0'[0]:
				numb = 10 * numb + conv(s[i]) - 48
			elif s[i] == b'-'[0]:
				sign = -1
			elif s[i] != b'\r'[0]:
				A.append(sign * numb)
				numb = zero
				sign = 1
			i += 1
	except:
		pass
	if s and s[-1] >= b'0'[0]:
		A.append(sign * numb)
	return A
main()


(n, m) = list(map(int, input().split()))
arr1 = list(map(int, input().split()))
arr2 = sorted(list(map(int, input().split())))
best = float('inf')
for item in arr2:
	diff = item - arr1[0] if item >= arr1[0] else m - arr1[0] + item
	new = [(arr1[i] + diff) % m for i in range(n)]
	if sorted(new) == arr2:
		best = min(best, diff)
print(best)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)

def toord(c):
	return ord(c) - ord('a')
mod = 998244353
INF = float('inf')
from math import factorial, sqrt, ceil, floor
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	(n, m) = RL()
	arra = RLL()
	arrb = RLL()
	arra.sort()
	arrb.sort()
	if arra == arrb:
		print(0)
	else:
		res = INF
		for i in range(n):
			now = arra[i]
			if now < arrb[0]:
				x = arrb[0] - now
			else:
				x = m - now + arrb[0]
			na = [(j + x) % m for j in arra]
			if sorted(na) == arrb:
				res = min(res, x)
		print(res)
main()


def p(a, b):
	a1 = sorted(a)
	b1 = sorted(b)
	if a1 == b1:
		return True
	else:
		return False
(n, m) = input().split()
n = int(n)
m = int(m)
a1 = input().split()
a2 = input().split()
a1 = [int(x) for x in a1]
a2 = [int(x) for x in a2]
xs = set([])
for i in a2:
	xs.add((i - a1[0]) % m)
r = 0
for j in xs:
	aux = []
	for k in a1:
		aux.append((k + j) % m)
	if p(aux, a2):
		r = j
print(r)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
for i in range(n):
	b.append(b[i] + m)
for i in range(n + n):
	if b[i] >= a[0]:
		c = [y + b[i] - a[0] for y in a]
		if c == b[i:i + n]:
			print(b[i] - a[0])
			break


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a = [i % m for i in a]
b = [i % m for i in b]
a = sorted(a)
b = sorted(b)
outcomes = set(sorted([(b[0] - i + m) % m for i in a]))
for x in outcomes:
	array = [(u + x) % m for u in a]
	if sorted(array) == b:
		print(x)
		break


def test(L1, L2, n):
	for i in range(n):
		if L2[i] - L1[i] != L2[0] - L1[0]:
			return False
	return True
ch = input()
L = [int(i) for i in ch.split()]
n = L[0]
m = L[1]
ch1 = input()
ch2 = input()
L1 = [int(i) for i in ch1.split()]
L2 = [int(i) for i in ch2.split()]
nb = 0
while True:
	L1.sort()
	L2.sort()
	if test(L1, L2, n) == True:
		break
	L2[0] += m
print((L2[0] - L1[0]) % m)


import sys
input = sys.stdin.readline

def check(a, b, x, m):
	a = [(i + x) % m for i in a]
	a.sort()
	return a == b
from collections import Counter as C
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
l = a[0]
aa = C(a)
bb = C(b)
cc = aa[a[0]]
ll = []
for i in bb:
	if bb[i] == cc:
		ll.append(i)
mi = 10000000000000000000
for i in ll:
	if i >= l:
		x = i - l
		if check(a, b, x, m):
			mi = min(i - l, mi)
	else:
		x = m - l + i
		if check(a, b, x, m):
			mi = min(x, mi)
print(mi)


import sys
input = sys.stdin.readline
from math import ceil, floor, factorial

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(1000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
(n, m) = int_array()
a = sorted(int_array())
b = sorted(int_array())
start = 1
for j in b:
	mset = set()
	for i in a:
		if j >= i:
			mset.add(j - i)
		else:
			mset.add(m + j - i)
	if start:
		ans = mset.copy()
		start = 0
	else:
		ans = ans.intersection(mset)
ans = sorted(list(ans))
for i in ans:
	this = []
	for j in a:
		this.append((j + i) % m)
	this.sort()
	if this == b:
		print(i)
		break


(n, m) = map(int, input().split())
a = sorted(list(map(int, input().split())))
b = sorted(list(map(int, input().split())))
c = m
for i in range(n):
	s = (m + b[i] - a[0]) % m
	for j in range(n):
		if (a[j] + s) % m != b[(i + j) % n]:
			break
	else:
		c = min(c, s)
print(c)


def do(i, j):
	global m
	if (i - j) % m == 0:
		return 0
	else:
		return m - (i - j) % m
(n, m) = map(int, input().split())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
b.sort()
x = [do(i, b[0]) for i in a]
x.sort()
for i in x:
	c = [(e + i) % m for e in a]
	c.sort()
	if c == b:
		break
print(i)


import sys
import math
input = sys.stdin.readline
(n, m) = map(int, input().split())
alist = list(map(int, input().split()))
blist = list(map(int, input().split()))
alist.sort()
blist.sort()
minx = math.inf
for i in range(n):
	diff = (blist[0] - alist[i] + m) % m
	arr = []
	for j in range(n):
		arr.append((alist[j] + diff) % m)
	arr.sort()
	flag = True
	for j in range(n):
		if arr[j] != blist[j]:
			flag = False
			break
	if flag:
		minx = min(minx, diff)
print(minx)


import sys
input = sys.stdin.readline
(n, m) = [int(item) for item in input().split()]
a = [int(item) for item in input().split()]
b = [int(item) for item in input().split()]
b.sort()
for item in a:
	a_mod = []
	for aa in a:
		a_mod.append((aa + m - item) % m)
	a_mod.sort()
	diff = b[0] - a_mod[0]
	ok = True
	for (aa, bb) in zip(a_mod, b):
		if bb - aa != diff:
			ok = False
			break
	if ok:
		print((diff - item + m) % m)
		exit()


(a, m) = map(int, input().split())
x = list(map(int, input().split()))
y = list(map(int, input().split()))
x.sort()
y.sort()
ans = 10000000000000000000
c = [0] * a
if x == y:
	print(0)
else:
	for i in range(0, a):
		if x[0] <= y[i]:
			h = y[i] - x[0]
		else:
			h = (y[i] - x[0]) % m
		for j in range(0, a):
			c[j] = (x[j] + h) % m
		c.sort()
		y.sort()
		if c == y:
			ans = min(h, ans)
	print(ans)


import math
(n, m) = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
a.sort()
b.sort()
ans = math.inf
for i in range(n):
	a1 = (b[0] - a[i] + m) % m
	c = []
	for j in range(n):
		c.append((a[j] + a1) % m)
	c.sort()
	if c == b:
		ans = min(ans, a1)
print(ans)


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import collections as col

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
MOD = 10 ** 9 + 7

def solve():
	(N, M) = getInts()
	A = sorted(getInts())
	B = sorted(getInts())
	A_set = sorted(list(set(A)))
	B_set = sorted(list(set(B)))
	C = []
	D = []
	for n in range(N):
		C.append((A[(n + 1) % N] - A[n]) % M)
		D.append((B[(n + 1) % N] - B[n]) % M)
	best = 10 ** 10
	for j in range(len(D)):
		if D[j:] + D[:j] == C:
			best = min(best, (B[j] - A[0]) % M)
	return best
print(solve())


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
ans = 10 ** 18
for i in range(n):
	if a[0] == b[i]:
		x = 0
	elif a[0] > b[i]:
		x = b[i] + m - a[0]
	else:
		x = b[i] - a[0]
	j = i
	count = 1
	check = True
	while count < n:
		j = (j + 1) % n
		if (a[count] + x) % m != b[j]:
			check = False
		count += 1
	if check:
		ans = min(ans, x)
print(ans)


(n, m) = map(int, input().split())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
l2.sort()
ans = m
for i in range(n):
	x = (l2[i] - l1[n - 1] + m) % m
	l3 = []
	for j in range(n):
		l3.append((l1[j] + x) % m)
	f = 0
	l3.sort()
	for j in range(n):
		if l3[j] != l2[j]:
			f = 1
			break
	if f == 0:
		ans = min(x, ans)
print(ans)


from collections import defaultdict as dc
import sys
import math
mod = 10 ** 9 + 7

def bs(a, x):
	i = bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return len(a)

def bs(a, b):
	l = a
	r = b + 1
	x = b
	ans = 0
	while l < r:
		mid = (l + r) // 2
		if x | mid > ans:
			ans = x | mid
			l = mid + 1
		else:
			r = mid
	return ans

def digit(n):
	a = []
	while n > 0:
		a.append(n % 10)
		n = n // 10
	return a

def inp():
	p = int(input())
	return p

def line():
	p = list(map(int, input().split()))
	return p

def opt(a, m, b, q, mid):
	p = q.copy()
	arr = a.copy()
	s = 0
	for i in range(len(arr)):
		arr[i] = (arr[i] + mid) % m
		if p[arr[i]] == 0:
			return 0
		p[arr[i]] = p[arr[i]] - 1
	return 1

def ans(a, b, p, z, m):
	pq = dc(int)
	xy = float('inf')
	for i in range(n):
		if a[i] <= z:
			x = z - a[i]
		elif a[i] > z:
			x = z + m - a[i]
		if pq[x] == 0:
			pq[x] = 1
			if opt(a, m, b, p, x):
				xy = min(xy, x)
	return xy
(n, m) = line()
a = line()
b = line()
p = dc(int)
a.sort(reverse=True)
z = max(b)
for i in b:
	p[i] += 1
if opt(a, m, b, p, 0):
	print(0)
else:
	print(ans(a, b, p, z, m))


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = [0] * n
d = b.copy()
d.sort()
sol = []
for i in range(n):
	x = (b[i] - a[0]) % m
	for j in range(n):
		c[j] = (a[j] + x) % m
	c.sort()
	if c == d:
		sol.append(x)
print(min(sol))


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
xl = []
for i in range(n):
	xl.append((b[0] - a[i]) % m)
xl.sort()
res = 0
for x in xl:
	s = {}
	for i in range(n):
		d = (a[i] + x) % m
		if d in s:
			s[d] += 1
		else:
			s[d] = 1
	for i in range(n):
		if b[i] in s:
			s[b[i]] -= 1
		else:
			break
	for (k, v) in s.items():
		if v != 0:
			res = 0
			break
		else:
			res = x
	if res:
		break
print(res)


def input_int_list():
	return list(map(int, input().split(' ')))
(n, m) = map(int, input().split(' '))
a = input_int_list()
b = input_int_list()
a.sort()
b.sort()
from collections import deque
a = deque(a)
solved = False
total_offsets = 0
while True:
	diff = b[0] - a[0]
	solved = True
	for i in range(1, n):
		if diff < 0 or b[i] - a[i] != diff:
			offset = m - a[-1]
			total_offsets += offset
			for j in range(n):
				a[j] += offset
			while a[-1] == m:
				a.pop()
				a.appendleft(0)
			solved = False
			break
	if solved:
		break
print(total_offsets + (diff + m) % m)


from collections import OrderedDict
(n, m) = list(map(int, input().split(' ')))
a = list(map(int, input().split(' ')))
b = list(map(int, input().split(' ')))
a.sort()
b.sort()

def diff(a, b, off):
	ans = -1
	for i in range(n):
		v = b[(i + off) % n] - a[i]
		if v < 0:
			v = m + v
		if ans != -1 and ans != v:
			return 1000000000.0
		ans = v
	return ans
mn = int(1000000000.0)
for i in range(n):
	mn = min(diff(a, b, i), mn)
print(mn)


[n, m] = list(map(int, input().split(' ')))
arrA = list(map(int, input().split(' ')))
arrB = list(map(int, input().split(' ')))

def diff_mod(a, b, m):
	result = 0
	if a <= b:
		result = b - a
	else:
		result = b - a + m
	return result

def arr_sum_mod(arr, n, m):
	new_arr = []
	for a in arr:
		new_arr.append((a + n) % m)
	return new_arr

def validate_permutation(arrA, arrB, diff, m):
	new_arr = arr_sum_mod(arrA, diff, m)
	return sorted(new_arr) == sorted(arrB)
smaller_x = 10 ** 9
for i in range(n):
	diff = diff_mod(arrA[0], arrB[i], m)
	if diff < smaller_x and validate_permutation(arrA, arrB, diff, m):
		smaller_x = diff
print(smaller_x)


from collections import Counter, OrderedDict
from itertools import permutations as perm
from fractions import Fraction
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
(n, m) = gil()
(a, b) = (gil(), gil())
a.sort()
b.sort()
x = [0]
for v in b:
	if v >= a[0]:
		x.append(v - a[0])
	else:
		x.append(m + v - a[0])
x.sort()
for xi in x:
	c = []
	for ai in a:
		c.append((ai + xi) % m)
	c.sort()
	if c == b:
		print(xi)
		break


from collections import Counter

def check(num):
	new = []
	for i in a:
		new.append((i + num) % m)
	new.sort()
	if new == b:
		return True
	return False
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
c1 = Counter(a)
c2 = Counter(b)
d = {}
for i in c2:
	if c2[i] not in d:
		d[c2[i]] = [i]
	else:
		d[c2[i]].append(i)
ans = m
num = a[0]
for i in d[c1[num]]:
	x = (i - num) % m
	if check(x):
		ans = min(ans, x)
print(ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
a.sort()
pos = 0
mn = float('inf')
while pos < n:
	if mn != float('inf'):
		break
	for j in range(n):
		x = (b[j] - a[pos]) % m
		temp = [(a[i] + x) % m for i in range(n)]
		if sorted(temp) == b:
			mn = min(mn, x)
	pos += 1
print(mn)


import collections
(N, M) = map(int, input().split())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
ans = float('inf')
cnt = collections.Counter(B)
a = A[0]
for b in B:
	if b < a:
		b += M
	x = b - a
	cnt2 = collections.Counter([(a + x) % M for a in A])
	if cnt2 == cnt:
		ans = min(ans, x)
print(ans)


(n, m) = map(int, input().split())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
count_a = 0
candidates = set()
(freqs_a, freqs_b) = (dict(), dict())
for x in a:
	if x in freqs_a:
		freqs_a[x] += 1
	else:
		freqs_a[x] = 1
for y in b:
	if y in freqs_b:
		freqs_b[y] += 1
	else:
		freqs_b[y] = 1
temp = a[0]
for y in freqs_b:
	if freqs_b[y] == freqs_a[temp]:
		candidates.add((y - a[0]) % m)
candidates = list(candidates)
candidates.sort()
trial = True
while trial:
	for c in candidates:
		if trial:
			possible = True
			for x in freqs_a:
				if (x + c) % m not in freqs_b:
					possible = False
				elif freqs_b[(x + c) % m] != freqs_a[x]:
					possible = False
			if possible:
				print(c)
				trial = False


from collections import defaultdict as dd
(n, m) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
occA = dd(int)
occB = dd(int)
for a in A:
	occA[a] += 1
for b in B:
	occB[b] += 1
a0 = A[0]
best = 10 ** 10
blist = list(occB.keys())
for b in blist:
	diff = (b - a0) % m
	for (a, v) in occA.items():
		if v != occB[(a + diff) % m]:
			break
	else:
		best = min(best, diff)
print(best)


(n, m) = map(int, input().split())
a = sorted(list(map(int, input().split())))
b = sorted(list(map(int, input().split())))
currSmallest = m
for i in range(n):
	curr = (b[i] - a[0]) % m
	flag = True
	for j in range(1, n):
		if (b[(i + j) % n] - a[j]) % m != curr:
			flag = False
			break
	if flag:
		currSmallest = min(curr, currSmallest)
print(currSmallest)


import os, io, sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import Counter
(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a1 = Counter(a)
b1 = Counter(b)
a1k = sorted(list(a1.keys()))
b1k = sorted(list(b1.keys()))
a1n = len(a1)
b1n = len(b1)
f = 0
out = sys.maxsize
for i in range(a1n):
	s = 0
	for j in range(i, i + a1n):
		if b1[b1k[j % a1n]] == a1[a1k[j - i]]:
			if j - i > 0 and (b1k[j % a1n] - b1k[(j - 1) % a1n]) % m == a1k[j - i] - a1k[j - i - 1]:
				s += 1
			elif j - i == 0:
				s += 1
			else:
				break
		else:
			break
	if s == a1n:
		out = min(out, (b1k[i] - a1k[0]) % m)
print(out)


(n, m) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
a.sort()
b.sort()
flag = 0
fir = 0
ans = 0
for i in range(n):
	flag = 0
	temp = (m - a[0] + b[i]) % m
	for j in range(n):
		if (m - a[j] + b[(j + i) % n]) % m != temp:
			flag = 1
			break
	if flag == 0 and fir == 0:
		fir = 1
		ans = temp
	elif flag == 0 and fir != 0:
		ans = min(ans, temp)
print(ans)


(n, m) = map(int, input().split())
a = sorted(list(map(int, input().split())))
b = sorted(list(map(int, input().split())))
l = len(b)
for i in range(l):
	b.append(m + b[i])
ans = 987654321
for i in range(n):
	isEnded = True
	diff = b[i] - a[0]
	for j in range(1, n):
		if diff != b[i + j] - a[j]:
			isEnded = False
			break
	if isEnded == True:
		currAns = diff
		if currAns < 0:
			currAns += m
		ans = min(ans, currAns)
print(ans)


(n, m) = list(map(int, input().split()))
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
l1.sort()
l2.sort()
l = []
for i in range(n):
	l.append((l2[0] - l1[i]) % m)
l = list(set(l))
l.sort()
for j in l:
	r = []
	for k in range(n):
		r.append((l1[k] + j) % m)
	r.sort()
	if r == l2:
		print(j)
		break


(n, m) = map(int, input().split())
arr1 = list(map(int, input().split()))
arr2 = list(map(int, input().split()))
from collections import Counter
count1 = Counter(arr1)
count2 = Counter(arr2)
ans = []
myset = set()
count = 0

def find(count, val):
	ans = []
	for key in count:
		if count[key] == val:
			ans.append(key)
	return ans

def findx(arr, key, m):
	ans = []
	for val in arr:
		if key <= val:
			ans.append(val - key)
		else:
			ans.append(val + (m - key))
	return ans
for (key, val) in count1.items():
	tmp = find(count2, val)
	lst = findx(tmp, key, m)
	if count == 0:
		ans = lst
		for val in ans:
			myset.add(val)
	else:
		myset1 = set(lst)
		myset = myset.intersection(myset1)
	count += 1
print(sorted(list(myset))[0])


(N, K) = map(int, input().split())
L1 = list(map(int, input().split()))
L2 = list(map(int, input().split()))
L1.sort()
L2.sort()
if L1 == L2:
	print(0)
else:
	mini = float('inf')
	for i in range(N):
		X = L1.copy()
		diff = (L2[i] - L1[0]) % K
		if diff <= 0:
			diff = diff + K
		for j in range(N):
			X[j] = (X[j] + diff) % K
		X.sort()
		if X == L2:
			if diff < mini:
				mini = diff
	print(mini)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
min1 = []
b.sort()
length = len(a)
for i in range(length):
	if a[0] > b[i]:
		min1.append(m - (a[0] - b[i]))
	else:
		min1.append(b[i] - a[0])
min1.sort()
l = []
for i in min1:
	l = [(a[j] + i) % m for j in range(n)]
	l.sort()
	if l == b:
		print(i)
		break