#include <bits/stdc++.h>
using namespace std;
const long long inf = 0x3f3f3f3f3f3f3f3f;
const long long N = 800000;
long long n, m;
long long a[N + 1], b[N + 1];
long long A(long long x) {
  return upper_bound(a + 1, a + 4 * n + 1, x) - a - 1;
}
long long B(long long x) {
  return upper_bound(b + 1, b + 4 * n + 1, x) - b - 1;
}
long long q[N], head, tail;
bool chk(long long x) {
  head = tail = 0;
  for (long long i = n + 1; i <= 3 * n; i++) {
    while (head < tail && q[tail - 1] - 1 - B(a[q[tail - 1]] - x - 1) >=
                              i - 1 - B(a[i] - x - 1))
      tail--;
    q[tail++] = i;
    while (head < tail && q[head] <= i - n) head++;
    if (q[head] - 1 - B(a[q[head]] - x - 1) < i - B(a[i] + x)) return false;
  }
  return true;
}
signed main() {
  cin >> n >> m;
  for (long long i = 1; i <= n; i++)
    scanf("%lld", a + i), a[i + 3 * n] = a[i] + 3 * m,
                                    a[i + 2 * n] = a[i] + 2 * m,
                                    a[i + n] = a[i] + m;
  for (long long i = 1; i <= n; i++)
    scanf("%lld", b + i), b[i + 3 * n] = b[i] + 3 * m,
                                    b[i + 2 * n] = b[i] + 2 * m,
                                    b[i + n] = b[i] + m;
  sort(a + 1, a + 4 * n + 1);
  sort(b + 1, b + 4 * n + 1);
  long long ans = m;
  for (long long i = 30; ~i; i--)
    if (ans - (1ll << i) >= 0 && chk(ans - (1ll << i))) ans -= 1ll << i;
  cout << ans;
  return 0;
}
