We need to find the smallest non-negative integer x such that after adding x modulo m to each a_i, we can get a multiset that matches b's multiset. So essentially, we need to find x such that the multiset {(a_i + x) mod m} equals the multiset {b_i}.
Let A be the list of a_i, B the list of b_i.
We need to find x where after applying the shift to A (mod m), we can permute to match B. Since we can permute, the multiset condition is sufficient.
So we need the smallest x >= 0 such that multiset {(a_i + x) mod m} = multiset {b_i}.
Let’s denote A' = (a_i + x) mod m.
Given that m can be up to 1e9, n up to 2000, so we cannot iterate all x.
We need to compute the smallest x that makes multisets equal.
Observation: For a fixed x, condition is that sorting A' gives sorted B. Since n is only 2000, we could test candidate x's efficiently.
The problem: There is guaranteed at least one x.
How many candidate x? Possibly O(n) candidates.
Let's think.
Given sorted A and sorted B, we can think of matching A shifted by x to B. Since modulo operation complicates things because values wrap around.
If we sort A (non-decreasing) and sort B (non-decreasing). For a given x, we compute A' = (a_i + x) mod m. Then we need to check if sorting A' gives exactly B.
But because of wrap-around, the sorted order of A' is not simply A sorted plus x mod m; it may split due to values crossing m.
Suppose we add x to each a_i. If no wrap-around occurs (i.e., for all i, a_i + x < m), then A' = a_i + x, sorted order same as sorted A. Then we need sorted A plus x equals sorted B. So x = B[0] - A[0] (mod?) but careful: because we need entire array equal after sorting: if (a_i + x) sorted equals sorted B, then each element matches: sorted_A[i] + x = sorted_B[i] for all i. That would mean x = sorted_B[0] - sorted_A[0] (must be same for all i). So in this no-wrap case, x is forced to be the difference between corresponding elements if the difference is constant across all i.
But wrap-around can happen: some elements may exceed m-1 and wrap to small numbers. In that case, the sorted order of A' may be: the ones that wrapped (i.e., a_i + x >= m) become small numbers (0 <= (a_i+x)-m < something). So the sorted A' will consist of two parts: the wrapped ones (which are small) and the non-wrapped ones (which are larger). After sorting, we would have first the wrapped ones (increasing) then the non-wrapped ones (increasing). This resembles a circular shift of sorted A.
More generally, we can consider the circular matching: we have two multisets of numbers modulo m. We want to find x such that A + x (mod m) as a multiset equals B. This is equivalent to: if we sort A and B, then there exists a rotation index k (0 <= k < n) such that after adding x to A, the sorted A' (which is a rotation of sorted A + x) matches sorted B. Actually, we need to formalize.
Let’s sort A: let a_sorted[0..n-1] ascending.
Let b_sorted[0..n-1] ascending.
We need to find x such that the multiset { (a_sorted[i] + x) mod m } equals multiset { b_sorted[i] }.
This is similar to checking if two circular sequences match after a shift.
Consider the differences between consecutive elements in sorted A and B, but modulo m wrap-around complicates due to wrap.
Idea: For each i (0 <= i < n), consider the candidate x = (b_sorted[0] - a_sorted[i] + m) mod m. Why? Because we think that after adding x, the element a_sorted[i] becomes b_sorted[0] (or some b element). Since we can permute, we can match any a element to any b. However, if we know which a element becomes which b after sorting? Actually, when we shift A by x, the sorted A' is determined; we need it to equal sorted B. So there must be some mapping between indices after sorting. In sorted order, the smallest element of A' should equal smallest of B. So the smallest element in A' must be b_sorted[0]. Which a_i becomes that? It could be the one that after adding x yields the smallest value. That smallest could be from an element that wraps (giving a small number) or from the smallest non-wrapped. In any case, the element that yields b_sorted[0] is some a_j. So we can try for each j, set x = (b_sorted[0] - a_sorted[j] + m) mod m. That is one candidate x. Then we need to check if this x works.
But is it guaranteed that the smallest x that works corresponds to some such candidate? Possibly yes, because if x works, then the multiset matches. In the sorted A' list, the first element is some (a_i + x) mod m = b_sorted[0]. That a_i is some element from original A (not necessarily sorted? but after sorting A', the smallest element corresponds to some a element; but we can think of the unsorted array: there is some a_j such that (a_j+x) mod m is the smallest among all. That smallest must equal b_sorted[0] because after sorting the multiset matches. So x must satisfy that for some a_j, (a_j+x) mod m = b_sorted[0]. So x is congruent to b_sorted[0] - a_j mod m. So indeed the correct x must be among those n candidates. Since there is at least one solution, at least one of these candidates works. So we can test each candidate x (n up to 2000) and check if it yields the multiset equality. Then pick the smallest non-negative x among those that work. Complexity O(n^2 log n) if we sort A' each time? But we can do O(n log n) per candidate? That's O(n^2 log n) ~ 4e6log? Actually n=2000, n^2=4e6, plus sorting of size n per candidate would be n * n log n = 20002000log2000 ~ 4e611 = 44e6, still okay. But we can maybe do O(n log n) total using matching technique? However with n=2000, O(n^2) is fine. 2000^2 = 4e6, plus sorting each candidate O(n log n) leads to about 4e6 + 2000 * (2000 log 2000) ≈ 4e6 + 2000200011 ≈ 4e6 + 44e6 = 48e6 operations, still within time if implemented efficiently in C++ (the problem likely expects O(n^2) solution). But we can do smarter: for each candidate, we can compute A' as an array, sort it, compare to sorted B. That's O(n log n) per candidate. n=2000, 20002000log2000 ~ 44e6 comparisons, okay. In Python, 44e6 operations might be borderline but still possible with optimization? However typical Codeforces problems with n=2000 allow O(n^2) in Python if optimized (maybe using list comprehensions and sorting). Sorting each 2000-length list 2000 times: 2000 * (2000 log 2000) ~ 2000 * (200011) = 44e6 comparisons, each comparison of integers is fast, but Python sorting overhead for many small lists might be okay? 2000 sorts of 2000 items each. Sorting 2000 ints in Python is fast: say 0.0002 seconds? Actually sorting 2000 ints might be ~0.1 ms? Not sure. 2000 sorts could be 0.2 seconds? But Python overhead might be larger. In practice, 2000 sorts of 2000 elements each is about 4 million element placements? Actually sorting complexity: O(N log N) comparisons, but each comparison may involve Python-level integer comparisons which are relatively fast. For 2000log2(2000)~2000*11=22000 comparisons per sort, times 2000 = 44 million comparisons. That's maybe 0.5-1 sec in CP Python? Might be okay if optimized. But we can reduce constant: we can pre-sort B once. For each candidate x, we compute array A_shifted = [(a_i + x) % m for i in range(n)], then sort it, then compare elementwise with sorted B. If equal, candidate works.
But we might be able to test faster by using multiset (Counter) and checking if Counter(A_shifted) == Counter(B). Building Counter for each candidate also O(n). But sorting might be similar.
But note: The candidate x may be up to m-1 (which can be 1e9). That's fine.
Edge Cases: If there are multiple a_j that produce same candidate x? Then we may test duplicate x. We can deduplicate candidates via set, but n is small; duplicates not heavy.
Thus algorithm:
- Read n, m.
- Read list a, b.
- Sort b to get b_sorted.
- Possibly sort a? We need a list of a elements for candidate generation. We can keep a as is.
- For each a_j in a (or perhaps for each distinct a_j), compute x = (b_sorted[0] - a_j) % m (i.e., (b_sorted[0] - a_j + m) % m). Collect candidates.
- For each candidate x (non-negative integer less than m), compute shifted = [(a_i + x) % m for a_i in a], sort it, compare with b_sorted.
- Keep track of smallest x that works.
But careful: The reasoning that the smallest element in A' must equal b_sorted[0] assumes that in the sorted multiset of A' the first element is indeed b_sorted[0]. Since b_sorted is sorted, if multisets equal, then after sorting A', the first element must be the smallest element of B, which is b_sorted[0]. So yes. So candidate generation is valid.
But what if there are multiple b elements equal to b_sorted[0]? That's fine; the smallest element is that value, and some a_j + x mod m must equal that value. It could be that more than one a_j yields that value, but we only need one.
Thus candidates are at most n (distinct a_j). However, consider case where the smallest element in A' is not unique, i.e., multiple elements equal b_sorted[0]. That's fine; we just need at least one a_j such that (a_j + x) mod m = b_sorted[0]. So our candidate generation is still sufficient.
Thus O(n^2 log n) works.
But can there be a scenario where the correct x is not among these candidates? Suppose x works, and the smallest element in A' is b_sorted[0]. Then there exists some a_j such that (a_j + x) mod m = b_sorted[0]. So x ≡ b_sorted[0] - a_j mod m. So indeed candidate list includes that x. So it's correct.
But is it possible that the smallest element in A' is not b_sorted[0]? No, because sorted A' equals sorted B, so the smallest element of A' equals smallest of B. So yes.
Thus candidate set is complete.
Now we need the smallest non-negative x. Since we test all candidates, we can compute min.
But what about x=0? It may be candidate if b_sorted[0] equals some a_j (i.e., b_sorted[0] - a_j ≡ 0 mod m). So we will test.
Potential issue: m can be 1. Then all numbers are 0. Then b_sorted[0] = 0. For each a_j=0, candidate x=0. x=0 works. That's fine.
Now, check example:
Example 1: n=4,m=3, a=[0,0,2,1], b=[2,0,1,1]. Sorted b = [0,1,1,2]? Actually sort b: [0,1,1,2]. b_sorted[0]=0. Candidates: For a_j: 0 -> x=0; 0 -> 0; 2 -> x= (0-2)%3 = 1; 1 -> (0-1)%3 = 2. So candidates:0,1,2. Test:
x=0: shifted = [0,0,2,1] sorted -> [0,0,1,2] not equal to [0,1,1,2] fails.
x=1: shifted = [1,1,0,2] sorted -> [0,1,1,2] equals b_sorted? Actually b_sorted = [0,1,1,2] yes. So works. x=1 is answer.
x=2: shifted = [2,2,1,0] sorted -> [0,1,2,2] not equal. So answer 1.
Example 2: n=3,m=2, a=[0,0,0], b=[1,1,1]. Sorted b = [1,1,1], b_sorted[0]=1. Candidates: for a_j=0: x = (1-0)%2 = 1 each; so only candidate 1. Test: shifted = [1,1,1] sorted = [1,1,1] matches. So answer 1.
Example 3: n=5,m=10, a=[0,0,0,1,2], b=[2,1,0,0,0]. Sorted b = [0,0,0,1,2] b_sorted[0]=0. Candidates: for a_j: 0 ->0, 0->0, 0->0, 1 -> (0-1)%10=9, 2 -> (0-2)%10=8. Test x=0: shifted = [0,0,0,1,2] sorted = [0,0,0,1,2] equals b_sorted, works. So answer 0.
So algorithm works on examples.
Now we must consider performance. n up to 2000, so O(n^2 log n) ~ 20002000log2000 = about 44 million operations. In Python, 44 million integer operations plus sorting overhead might be okay within 2 seconds? Possibly borderline but often accepted if optimized. We can try to reduce constant.
We could avoid sorting each time by using a multiset matching approach: For a given x, we want to check if multiset A' equals multiset B. Since B is fixed, we could pre-sort B. For each candidate, we could compute A' and sort it. Sorting is O(n log n). That's acceptable.
But maybe we can do O(n^2) by using a frequency table? m is large so not indexable. We could sort A as well, and then for each candidate x, we can try to align the two sorted lists after adjusting for wrap. There's an alternative approach: after sorting A, the shifted array modulo m when sorted is essentially a rotation of the sorted A (with each element increased by x, but those that exceed m wrap to start). More formally, if we sort A, then compute the circular differences? There is known approach for this problem (likely from Codeforces): "Make it Equal" or something. Actually this is Codeforces Round problem? Possibly "Equalize" etc. Let's think.
Given sorted A = a0 <= a1 <= ... <= a_{n-1}. For a given x, define A' = [ (a_i + x) % m ]. Sort A'. The sorted A' will consist of two segments: those a_i with a_i + x >= m (i.e., a_i >= m - x) produce values (a_i + x - m) which are smaller than x? Actually they produce values from 0 to (a_i + x - m). While those with a_i + x < m produce values from (a_? + x) to m-1. After sorting, the wrapped values (the small ones) come first, then the non-wrapped. So the sorted A' is a rotation of the sorted A plus x? Actually if we take the sorted A and add x to each, then take modulo m, then sort, we effectively split at some index k where a_k is the first element that after adding x does not wrap. Then sorted A' = [ (a_k + x - m), ..., (a_{n-1} + x - m), (a_0 + x), ..., (a_{k-1} + x) ]? Wait careful: Those that wrap are the ones with a_i + x >= m, i.e., a_i >= m - x. Since a_i sorted, the ones that wrap are the largest elements. So let k = number of elements that do NOT wrap? Actually let's define: Let L be the set of indices i such that a_i + x < m (no wrap). Since a_i increasing, these are the smallest ones. Then the others (largest ones) wrap. So sorted A' will be: first the wrapped ones (which are small after subtraction), then the non-wrapped ones (which are larger). But note: Wrapped ones: for each a_i where a_i + x >= m, value = a_i + x - m. Since a_i is large, a_i + x - m might be? For large a_i, a_i + x - m is roughly (a_i - (m - x)). Since a_i >= m - x, this is between 0 and a_{n-1} + x - m. The wrapped values might be larger than some non-wrapped ones? Actually if x is small, wrapped values are small because they are just a_i - (m - x) which could be as low as 0 (if a_i = m - x). The non-wrapped values are from a_0 + x to a_{L-1} + x (where L is count of no-wrap). Since a_0 + x is at least x (maybe 0). Typically, wrapped values are all less than (a_{n-1} + x - m). a_{n-1} + x - m could be less than a_0 + x? Possibly yes, but not necessarily. Let's consider example: m=100, A = [10,20,90], x=20. Then no-wrap: 10+20=30 <100, 20+20=40 <100; wrap: 90+20=110-100=10. So wrapped value is 10, non-wrapped are 30,40. Sorted A' = [10,30,40] => indeed wrapped small, then non-wrapped. So order: wrapped values are from the largest original a_i, but after wrap they become small, often smaller than the non-wrapped ones. So sorted A' = [ (a_i + x - m) for i where a_i >= m-x ] sorted increasingly, then [ (a_i + x) for i where a_i < m-x ] sorted increasingly.
Thus sorted A' is not a simple rotation of sorted A; it's a concatenation of two sorted sublists.
Now, we want sorted A' to equal sorted B. So we can attempt to match sorted B with this structure. For a candidate x derived from pairing b0 with some a_j, we can deduce which a_j becomes b0. Then we can try to see if the whole sequence matches.
Alternative O(n^2) method without sorting per candidate: For each candidate x, we can compute A' as list, then sort it and compare. Since n=2000, sorting per candidate is acceptable.
Given that we need to implement in Python, I'll proceed with the straightforward approach.
Potential optimization: Use Counter (dictionary) to compare multisets. But building Counter involves hashing n elements, which is O(n). Sorting also O(n log n). In Python, sorting 2000 ints might be faster than building a Counter? We'll test mentally: Sorting 2000 ints uses Timsort, which is efficient. Building Counter via dict incurs overhead of hash and updates. Both are okay.
We can also early break if mismatches during sorted comparison after sorting.
But we must be careful about memory and time.
Now, is it possible that the smallest x is not from candidate b_sorted[0] - a_j? Wait we argued it must be because the smallest element matches b_sorted[0]. However, consider the case where after shifting, the multiset matches but the smallest element of A' might not be b_sorted[0] because there could be multiple elements with same smallest value? No, the smallest element of A' must be equal to the smallest element of B, which is b_sorted[0]. So it's correct.
But what about the possibility that after shifting, there is some wrap causing the smallest element to be from some a_j, but there could be multiple a_j that produce the same value as b_sorted[0]? That's fine, we still consider that candidate.
Thus candidate set covers all possible x.
Now we need to find the smallest non-negative integer x. Since m can be large, x can be up to m-1. Among all candidates, we choose min. However, note that if a candidate is computed as (b_sorted[0] - a_j) mod m, this yields a number in [0, m-1]. But there could be smaller x that is not this? Not possible.
But what about the scenario where b_sorted[0] appears multiple times, and the smallest element in A' could be b_sorted[0] but we might need to match the smallest element to a particular a_j? Actually the candidate x is based on a_j such that (a_j + x) mod m = b_sorted[0]. For a given x that works, there could be multiple a_j satisfying that, but any one gives that x when computing candidate. So x is in the candidate list.
Thus algorithm stands.
Edge Cases: n=1. Then a=[a0], b=[b0]. We need x such that (a0+x)%m = b0. So x = (b0 - a0) mod m. That is candidate (since b_sorted[0]=b0). So answer is that.
Now, one more nuance: When we generate candidates using b_sorted[0] and each a_j, we get n values. However, it's possible that two different a_j give the same x. That's fine. We can deduplicate to reduce work. But n small, we can just test all, but we might test the same x multiple times. That's fine; we can break after finding min, but we need to compute min over all that work. However, we could collect distinct candidates in a set, then sort them ascending, and test smallest first until we find a working x, then that's answer. But we must find the smallest x that works, not necessarily the smallest candidate that works? Actually if we test candidates in increasing order, the first that works is the answer. So we can compute all distinct candidates, sort them, and test in ascending order until find a working one, then output. That could be faster in average case. But worst-case may need to test many.
However, we can't guarantee that the smallest candidate is the answer? The answer is the smallest x among those that work, not necessarily the smallest candidate overall? But if we test candidates in increasing order, the first that works is indeed the smallest x that works, because any smaller x would also be a candidate? Actually not necessarily: There might be a smaller x that is not a candidate? But we argued all possible x that work are among the candidates. So the set of working x is a subset of the candidate set. Therefore, the smallest working x is the smallest element in the intersection. If we sort the candidate set (distinct) and test in increasing order, the first working is the smallest working. So that is efficient.
But careful: The candidate set is derived from each a_j, and there might be a candidate x that is not a valid solution but is smaller than the true answer; we might test it and it fails, then later test the true answer. So it's fine.
Thus we can:
- compute distinct_x = set()
- for each a_j, x = (b0 - a_j) % m; add to set.
- sort list_x = sorted(distinct_x)
- For each x in list_x:
compute shifted = [(a_i + x) % m for i in range(n)]
sort shifted
if shifted == sorted_b: print(x); return
Since we need to output the smallest non-negative x, we test ascending.
Complexities: at most n=2000 distinct candidates. So at most 2000 checks, each O(n log n). That's fine.
Potential micro-optimizations: Pre-sort b once. Pre-store a as list. For each x, we need to generate shifted list. Could we avoid sorting each time by using a pre-sorted A? Possibly we can use a different check: For each candidate x, we can try to match by a two-pointer method using sorted A and sorted B? Let's examine if we can check in O(n) per candidate using the structure.
Given sorted A and sorted B, for a candidate x, we can determine which elements wrap: those with a_i >= m - x (if x>0; if x=0 then none wrap). But m-x could be large; but we can compute threshold. Then we can construct the expected sorted A' by taking wrapped part: for each a_i >= m-x, compute value = a_i + x - m, and collect them; they are sorted because a_i is increasing, and a_i + x - m is increasing as well (since derivative 1). Actually if a_i increases by 1, the wrapped value increases by 1, so it's increasing. Similarly non-wrapped values a_i + x for a_i < m-x are increasing. So the sorted A' is concatenation: wrapped values (increasing) followed by non-wrapped (increasing). But note that the wrapped values may be less than the non-wrapped? Not necessarily guaranteed but generally yes because the max wrapped value is (a_max + x - m) and the min non-wrapped is (a_min + x). It's possible that a_max + x - m >= a_min + x, i.e., a_max - m >= a_min, but since a_max < m, a_max - m is negative, so a_max + x - m < x <= a_min + x (if a_min >=0). Actually a_min could be 0, then a_min + x = x. a_max + x - m <= (m-1)+x - m = x-1, so it's less than x. So wrapped values are all less than x, non-wrapped are >= x, so they are separated. However, if a_min > 0, non-wrapped min is a_min + x, which is >= x (since a_min >0 maybe). Wrapped max is a_max + x - m, which is <= x-1 (since a_max <= m-1). So indeed wrapped values are all less than x, non-wrapped are >= x, so they are disjoint intervals. So concatenation is correct and sorted.
Thus sorted A' = [ (a_i + x - m) for i from first index where a_i >= m-x to n-1 ] + [ (a_i + x) for i from 0 to last index where a_i < m-x ].
Now we can compare this directly to sorted B without generating and sorting entire shifted list. This would be O(n) per candidate (just one pass merging or comparing). Since we have sorted A and sorted B, we can compute the expected sorted A' as above and compare elementwise.
Let's elaborate:
We have sorted A: a[0..n-1] ascending.
Given x, compute threshold T = m - x (if x > 0; if x == 0, then threshold = m? Actually a_i + x < m means a_i < m - x. For x=0, m-x = m, all a_i < m (since a_i < m), so no wrap. So we can handle uniformly: For any x, find the split index split = lower_bound of a for value (m - x). That is first index i where a[i] >= m - x. If no such, split = n (all no-wrap). Then wrapped indices: i from split to n-1. non-wrapped: i from 0 to split-1.
Now produce list A' in order:
- For i from split to n-1: value = a[i] + x - m.
- For i from 0 to split-1: value = a[i] + x.
This list is already sorted? Check: The values from wrapped part: they are increasing because a[i] increasing, and adding constant (x-m) preserves order. The values from non-wrapped part: also increasing. And as argued, max wrapped value = a[n-1] + x - m <= x-1, and min non-wrapped value = a[0] + x >= x (since a[0] >= 0). But careful: a[0] could be 0, then a[0] + x = x. And max wrapped is <= x-1, so all wrapped are < all non-wrapped. So concatenation is sorted. So A' is sorted as defined.
Thus we can compute this A' array in O(n) and then compare with sorted B (pre-sorted) elementwise. This avoids sorting each time.
Implementation steps:
- Read n,m.
- Read list a (n ints).
- Read list b (n ints).
- Sort a (we need sorted for this method) => a_sorted.
- Sort b => b_sorted.
- Let b0 = b_sorted[0].
- Compute candidate x_set = set()
For each val in a (original a? But we need a_sorted? Actually candidate generation uses a_j from original list? We can use any a_j; using original a is fine, but we need to use the values from a (the multiset). Since we have a_sorted, we can iterate over a_sorted (or original). But using a_sorted might be more convenient because later we use a_sorted in the checking. However candidate generation uses a elements; using a_sorted might produce duplicates if values repeat. That's fine; we will deduplicate via set. So we can iterate over a_sorted (or original) to generate candidates.
- Convert x_set to sorted list.
- For each x in sorted_x:
- Determine split: find first index i where a_sorted[i] >= m - x. Since a_sorted is sorted, we can use binary search (bisect_left) to get split. However note: When x=0, m-x=m, and all a_sorted[i] < m, so split = n (no wrap). This works.
- Build A_shifted_sorted list:
We can generate in two loops:
shifted = []
for i from split to n-1: shifted.append(a_sorted[i] + x - m)
for i from 0 to split-1: shifted.append(a_sorted[i] + x)
Or we can allocate an array of size n and fill accordingly.
- Compare shifted with b_sorted elementwise. If all equal, output x and return.
- Since guaranteed solution, we will find one.
Time complexity: O(n * (log n + n))? Actually for each candidate we do binary search O(log n) to find split, then O(n) to generate shifted and O(n) to compare. So per candidate O(n). With up to n candidates, O(n^2) = 4e6, which is great. And we also sort a and b initially O(n log n). So overall O(n^2) with low constant.
This is definitely efficient in Python.
Potential pitfalls:
-
When x is such that m - x is exactly equal to some a_i? Then that a_i satisfies a_i >= m - x? The condition for wrap is a_i + x >= m, i.e., a_i >= m - x. So if a_i = m - x, then a_i + x = m, which mod m is 0. So (a_i + x) mod m = 0. This value is considered wrapped? Actually it becomes 0, which is less than x typically (unless x=0). In our construction, we treat those indices as wrapped because a_i >= m - x. So they go into the first segment. That's correct because (a_i + x) mod m = 0, which is less than non-wrapped values which are >= x (since x > 0). So good.
-
For x=0, m - x = m, but all a_i < m, so split = n. Then the wrapped segment is empty; we only do second segment: a_sorted[i] + 0. So shifted = a_sorted. Compare to b_sorted. Works.
-
For large x close to m, say x = m-1, then m - x = 1. Then many a_i >=1 will wrap. The wrapped values are a_i + (m-1) - m = a_i -1. For a_i =0, a_i <1 so no wrap. So wrapped part includes indices from split where a_i >=1. Then wrapped values are a_i -1 (which may be negative? Actually a_i -1 could be negative if a_i =0? But a_i >=1 in wrapped part, so min a_i=1 gives wrapped value 0. So fine). Non-wrapped: only a_i=0 => value 0 + (m-1) = m-1. So shifted = [0, 0, ..., m-1? Actually careful: If there are multiple 0s, they become m-1, which is large. So shifted order: wrapped values (from a_i>=1) which are a_i-1 ranging from 0 up to (m-1)-1 = m-2, then non-wrapped values (only a_i=0) produce m-1. So sorted indeed. So algorithm works.
But we need to be careful about integer overflow? Python big ints fine.
Edge: m could be 1. Then x in {0} because (b0 - a_j) mod 1 = 0. For x=0, m-x = 1, all a_i <1? Actually a_i are 0 (since 0 <= a_i < m, m=1 => only 0). So split = 0? Because a_sorted[0] = 0, m-x =1, 0 >= 1? false. So split = n? Actually we need first index i where a_sorted[i] >= 1. Since a_sorted[0]=0 <1, no such index, so split = n. Then shifted = a_sorted + 0 = [0,...,0]. b_sorted also all zeros. Works.
Edge: x could be 0 and m=0? No m>=1.
Thus algorithm is solid.
Now, confirm that the candidate set indeed contains all possible x. But we used b_sorted[0] as the reference. However, if there is wrap, the smallest element in A' may come from a wrapped element. That's okay because we include that a_j in candidate generation. So covered.
But consider a scenario where b_sorted[0] appears multiple times. Suppose x works, and the smallest value in A' is v = b_sorted[0]. This v may be achieved by more than one a_j after shift. So x = (v - a_j) mod m for any such a_j. So candidate list includes it.
Now, what about the possibility that after shift, the smallest element in A' is not unique, and b_sorted[0] also appears multiple times. That's still fine.
Thus algorithm is correct.
But is there any case where the smallest element of A' is not b_sorted[0] because the multisets match but sorting? No, if multisets are equal, the sorted lists are identical. So smallest element of sorted A' equals smallest of sorted B.
Hence all good.
Now we need to implement.
Potential improvements: we can further reduce number of candidates by using only distinct a values? That's what set does. So at most n distinct.
Now, implementation details:
- Use bisect from Python: bisect_left(a_sorted, m - x) to get split.
- Build shifted list as: shifted = [0]*n; but we need to fill in order: first wrapped values, then non-wrapped. But we can just create list by concatenation: shifted = [a_sorted[i] + x - m for i in range(split, n)] + [a_sorted[i] + x for i in range(split)] . Then compare to b_sorted.
But note: The order of wrapped part should be increasing. Since a_sorted[i] for i from split to n-1 is increasing, the wrapped values a[i]+x-m are increasing as well. So that list is increasing. And the non-wrapped part from i=0 to split-1 is increasing. So concatenation is sorted.
One more check: The wrapped values could be negative? Since a_i >= m - x, a_i + x - m >= 0? Because a_i >= m-x, so a_i + x - m >= 0. So they are non-negative. And non-wrapped values a_i + x <= m-1? Actually a_i < m-x => a_i + x < m, so less than m. So all values in [0, m-1]. Good.
Now, check with example 1: a_sorted = [0,0,1,2] (but original a = [0,0,2,1] sorted => [0,0,1,2]? Actually 0,0,2,1 sorted => [0,0,1,2]. b_sorted = [0,1,1,2]. b0=0. Candidates: for a values: 0,0,1,2 => x = 0,0, (0-1)%3=2, (0-2)%3=1 => distinct {0,1,2}. Test x=0:
m-x=3, split = first index where a_sorted[i]>=3 => split=4 (since all <3) => shifted = [] + [0,0,1,2] = [0,0,1,2] != b_sorted [0,1,1,2] fail.
x=1:
m-x=2, split = first index where a_sorted[i]>=2? a_sorted = [0,0,1,2] => index 3 (value 2) because 2>=2, so split=3.
wrapped: i=3 => a[3]=2 => 2+1-3=0? Actually m=3, so 2+1-3=0.
non-wrapped: i=0,1,2 => values: 0+1=1, 0+1=1, 1+1=2? Actually a[2]=1 => 1+1=2. So shifted = [0] + [1,1,2] = [0,1,1,2] matches b_sorted. Good.
x=2:
m-x=1, split = first index where a_sorted[i]>=1? a_sorted[2]=1 => split=2.
wrapped: i=2,3 => a[2]=1 => 1+2-3=0; a[3]=2 => 2+2-3=1 => [0,1]
non-wrapped: i=0,1 => a[0]=0 => 0+2=2; a[1]=0 => 0+2=2 => [2,2]
shifted = [0,1,2,2] != b_sorted. So works.
Thus algorithm works.
Now, about candidate generation: Should we use original a list or sorted? Both produce same set of values but may have duplicates. We'll use original a list to generate candidates? But later we need sorted a for checking, so we will sort a anyway. But generating candidates from sorted a is fine as it yields the same set of distinct values. However, we must ensure we include all a values; duplicates don't matter.
But is there any scenario where using sorted a for candidate generation might miss a candidate that would be derived from an a value that is not present in sorted? No, sorted a contains all values from a (multiset). So it's fine.
So steps:
- a = list of ints
- b = list of ints
- a_sorted = sorted(a)
- b_sorted = sorted(b)
- b0 = b_sorted[0]
- candidate_x = set()
- for val in a_sorted: # or a
x = (b0 - val) % m
candidate_x.add(x)
- sorted_candidates = sorted(candidate_x)
Now, for each x in sorted_candidates:
# Compute split using bisect_left on a_sorted for m - x
split = bisect.bisect_left(a_sorted, m - x) # first index where a_sorted[i] >= m-x
# Build shifted sorted list
shifted = []
# Wrapped part
for i in range(split, n):
shifted.append(a_sorted[i] + x - m)
# Non-wrapped part
for i in range(0, split):
shifted.append(a_sorted[i] + x)
# Compare with b_sorted
if shifted == b_sorted:
print(x)
return
Now, we must consider that the candidate set might contain x that are not valid but we will test them. This is fine.
Now, is there any corner case where the computed shifted list does not match the sorted version of (a_i + x) % m? Let's verify that our construction indeed yields the sorted list. We argued it does because wrapped values are all less than non-wrapped. However, need to confirm that the wrapped part is sorted and the non-wrapped part is sorted, and that the maximum of wrapped part is less than the minimum of non-wrapped part.
Proof: For any i in wrapped indices (i >= split) and j in non-wrapped (j < split):
For wrapped: v_i = a_i + x - m. Since a_i >= m - x => v_i >= 0. Also a_i <= m-1 => v_i <= x-1.
For non-wrapped: v_j = a_j + x. Since a_j < m - x => v_j <= m-1 (but more importantly v_j >= x? Actually a_j >= 0, so v_j >= x). But wait: a_j could be 0, then v_j = x. So v_j >= x.
Since v_i <= x-1 < x <= v_j, we have v_i < v_j. So indeed all wrapped values are less than all non-wrapped values. Therefore concatenation yields a sorted list.
Thus correct.
Now, what about x=0? Then m - x = m, split = n (since no a_i >= m). So wrapped part empty, non-wrapped: a_sorted[i] + 0. So shifted = a_sorted. That's sorted.
Now, one more nuance: x could be 0, but if m - x = m, bisect_left on a_sorted for m: since all a_i < m, bisect_left returns n. Good.
Now, check case where x equals m? x is modulo m, we consider x in [0, m-1]. The candidate generation uses modulo, so x < m. So okay.
Now, let's test with some random scenario to be sure.
Take n=3, m=10, a=[0,5,7], b=[2,5,7]? But we need guarantee that solution exists. Let's design a scenario where x works.
Suppose a=[0,5,7], x=2 => shifted=[2,7,9] -> sorted [2,7,9]. b=[2,7,9]. So b_sorted=[2,7,9], b0=2. Candidates: (2-0)%10=2, (2-5)%10=7, (2-7)%10=5. So candidates {2,7,5}. Sorted: 2,5,7. Test x=2: m-x=8, split = first a_i >=8? a_sorted [0,5,7] => none >=8, split=3. shifted = [] + [0+2,5+2,7+2] = [2,7,9] matches b_sorted. Works. So answer 2.
Test x=5: would it work? Probably not.
Now test scenario where x causes wrap: a=[8,9,0], m=10, x=3 => shifted = [(8+3)%10=1, (9+3)%10=2, (0+3)=3] sorted = [1,2,3]. b=[1,2,3]. So b0=1. Candidates: (1-8)%10=3, (1-9)%10=2, (1-0)%10=1. Candidates {3,2,1}. Sorted:1,2,3. Test x=1: m-x=9, split = first a_i >=9? a_sorted [0,8,9] => index of 9 is 2? Actually a_sorted = [0,8,9]. m-x=9 => bisect_left for 9 gives index 2 (since a[2]=9). So split=2. Wrapped: i=2 => 9+1-10=0. Non-wrapped: i=0,1 => 0+1=1, 8+1=9? Wait 8+1=9 but check: 8<9? Actually non-wrapped condition: a_i < m - x => a_i < 9. For i=0:0<9 true; i=1:8<9 true; i=2:9<9 false => wrap. So non-wrapped values: 0+1=1, 8+1=9. So shifted = [0] + [1,9] = [0,1,9] which is not sorted? Wait we said wrapped values first: we compute wrapped values from i=2: value=0. Then non-wrapped: i=0->1, i=1->9. So list = [0,1,9] sorted? Indeed 0,1,9 is sorted, but b_sorted = [1,2,3]? Not match. So x=1 fails. x=2: m-x=8, split = first a_i >=8? a_sorted [0,8,9] => index 1 (a[1]=8) because 8>=8. So split=1. Wrapped: i=1,2 => values: 8+2-10=0, 9+2-10=1 => [0,1] (sorted). Non-wrapped: i=0 => 0+2=2 => [2]. So shifted = [0,1,2] which matches b_sorted? b_sorted = [1,2,3]? Actually we set b=[1,2,3], so not match. So x=2 fails. x=3: m-x=7, split = first a_i >=7? a_sorted [0,8,9] => index 1? Actually 8>=7 so split=1. Wrapped: i=1,2 => 8+3-10=1, 9+3-10=2 => [1,2]. Non-wrapped: i=0 => 0+3=3 => [3]. So shifted = [1,2,3] matches b_sorted. So works.
Thus the algorithm picks the correct x.
Now, consider scenario where there are duplicate values in a and b. Works.
Now, one more nuance: The candidate generation uses b_sorted[0]. However, if there are multiple b elements with the same smallest value, that's fine. But what about the case where after shift, the smallest element of A' is b_sorted[0] but there is also b_sorted[0] value in the non-wrapped part? That doesn't matter.
Now, is it possible that our construction of shifted sorted might be incorrect if wrapped part and non-wrapped part are not disjoint? We argued they are. But we need to ensure that the condition a_j < m - x for non-wrapped and a_i >= m - x for wrapped partitions all elements. And we argued that all wrapped values are < x, all non-wrapped values >= x, so indeed disjoint and order preserved. However, what about x=0? Then wrapped part is empty, and non-wrapped values are a_i; they are >=0. So fine.
Now, what about x = something where m - x = 0? That would mean x = m. But x is modulo m, so x < m, so m - x > 0 always. Actually if x=0, m-x=m>0. If x>0, m-x is between 1 and m-1 inclusive. So threshold is positive.
Now, what about x = something where m - x > m? Not possible.
Now, check with m=1: x must be 0. Then m-x=1, split = n, shifted = a_sorted (all zeros) matches.
Thus all good.
Now, we must guarantee that we find the smallest x. Since we iterate candidates in increasing order, we will find the smallest that works. But is it possible that there is a valid x that is smaller than any candidate? No, because all valid x are candidates. So the smallest valid x is the smallest candidate that passes the test.
But careful: The candidate list contains numbers derived from (b0 - a_j) mod m. This mod operation returns a number in [0, m-1]. The smallest valid x is among these. So we are fine.
Now, one more thought: Could the smallest valid x be something like 0? Yes.
Now, test a tricky scenario: m=10, a=[0,0,5], b=[5,5,0]? Let's check if there exists x. Suppose x=5: shifted = [5,5,0] matches b? Actually (0+5)=5, (0+5)=5, (5+5)%10=0 => [5,5,0] which matches b. So x=5 works. b_sorted = [0,5,5], b0=0. Candidates: (0-0)%10=0, (0-5)%10=5. So candidates {0,5}. Test x=0: shifted sorted = [0,0,5] vs b_sorted [0,5,5] fails. x=5 works. So answer 5. That is smallest? Could x=0 work? No. So output 5.
Now, consider another scenario: a = [2,3,8], m=10, b = [0,5,6]? Check if any x: x= ? Not sure. But guarantee says at least one exists.
Now, confirm that our method will correctly compute split for x=5: a_sorted = [0,0,5]? Wait a is [0,0,5] sorted = [0,0,5]. For x=5, m-x=5. split = first index where a_sorted[i] >= 5 => index 2 (value 5). Wrapped: i=2 => 5+5-10=0; Non-wrapped: i=0,1 => 0+5=5, 0+5=5 => shifted = [0,5,5] matches b_sorted [0,5,5]. Good.
Now, note: In this example, b0=0. The candidate x=0 came from a_j=0. That fails. x=5 from a_j=5 works.
Thus algorithm yields 5.
Now, check if there could be a scenario where candidate x works but our sorted construction fails because of duplicate values causing split threshold issues? Not likely.
Now, let's think about time: We do binary search per candidate (log n ~11) and then O(n) loops for building and comparing. So about 2000 * 2000 = 4e6 operations, which is fine.
Now, implement with Python's bisect module.
One nuance: In the building of shifted, we might be creating new lists each time, which is fine.
But we might further micro-optimize: Instead of constructing full list and then comparing, we could compare on the fly to b_sorted to early exit. For example, we can generate the wrapped values and compare to first part of b_sorted (size n - split). But it's simpler to just construct and compare.
But building list each time involves allocation and copying. With n=2000 and up to 2000 candidates, that's at most 4 million elements allocated, which is okay.
Now, handle large m (up to 1e9) but integer operations fine.
Now, one more thing: The candidate set may include x that are not valid, but we need to test them. But maybe we can reduce candidates further: Only need to consider distinct a values? Already done.
Now, we must guarantee that we indeed compute split correctly when m - x is larger than any a element. bisect_left returns n, which is correct.
Now, double-check the case where x is such that m - x is exactly equal to some a_i. That a_i is considered wrapped (since a_i >= m - x). That's correct because (a_i + x) % m = 0, which is less than any non-wrapped value (>= x). So it goes into wrapped part. So our split using bisect_left includes that index in wrapped because condition is a_i >= m - x. So correct.
Now, test with such case: m=10, a=[0,5,9], x=1 => m-x=9. a_sorted [0,5,9]. split = first index where >=9 => index 2 (value 9). Wrapped: i=2 => 9+1-10=0. Non-wrapped: i=0,1 => 0+1=1,5+1=6 => shifted = [0,1,6]. That seems correct: (9+1)%10=0, (0+1)=1, (5+1)=6. Sorted [0,1,6]. Good.
Now, test with x=9: m-x=1. split = first index where >=1 => a_sorted[1]=5? Actually [0,5,9], index 1 (5 >=1). Wrapped: i=1,2 => 5+9-10=4, 9+9-10=8 => [4,8]. Non-wrapped: i=0 => 0+9=9 => [9]. Shifted = [4,8,9]. Check actual: (0+9)=9, (5+9)%10=4, (9+9)%10=8; sorted [4,8,9]. matches.
Now, think about the possibility of multiple wrap segments? Actually only one wrap point because adding constant and modulo m is like rotating a circle: the values are (a_i + x) mod m, which can be seen as shifting on a circle. The sorted order after modulo corresponds to taking the circular order starting from the smallest value. Since we add constant, we shift the positions. Our two-segment approach is standard.
Thus algorithm stands.
Now, let's implement:
-
import sys, bisect
-
read lines: 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_sorted = sorted(a)
-
b_sorted = sorted(b)
-
b0 = b_sorted[0]
-
candidates = set()
-
for val in a: # can use a or a_sorted
x = (b0 - val) % m
candidates.add(x)
-
candidates_sorted = sorted(candidates)
-
for x in candidates_sorted:
compute split
split = bisect.bisect_left(a_sorted, m - x)
build shifted
shifted = []
wrapped part
for i in range(split, n):
shifted.append(a_sorted[i] + x - m)
non-wrapped part
for i in range(0, split):
shifted.append(a_sorted[i] + x)
compare
if shifted == b_sorted:
print(x)
return
Because we have to output answer.
But we must consider the possibility that the candidate x may be large (close to m-1), and in building shifted we compute a_sorted[i] + x - m; since a_sorted[i] < m, x - m is negative, but a_sorted[i] + x - m is non-negative because a_sorted[i] >= m - x for wrapped indices, so the sum is >=0. However, Python ints are fine.
Now, test with some edge cases:
Case: n=2000, all a_i = 0, b_i = 0. Then b0=0, candidates = {0}. x=0: split = bisect_left(a_sorted, m) => n (since all 0 < m). shifted = [] + [0]*n = b_sorted (all zeros). So answer 0.
Case: n=2000, a_i all distinct? Not needed.
Now, we must ensure that when x is such that m - x > max(a_sorted), split = n, then shifted = [a_i + x] but note that a_i + x may exceed m-1? Actually if m - x > max(a_sorted), then for all i, a_i < m - x, so a_i + x < m. So values are in [x, max(a)+x] which may be up to < m. So shifted is just a_sorted + x, sorted. That matches.
Now, if x is such that m - x <= min(a_sorted), then split = 0, wrapped includes all elements, shifted = [a_i + x - m] sorted. That is also fine.
Now, we should consider possible pitfalls: The candidate set is derived using b0. But what if b0 is not unique and the smallest element in A' might be b0, but we might be trying to match a specific a_j to b0? Actually we don't need to know which a_j; we just need to test x. Our test uses entire multiset, so it's fine.
Now, confirm with a case where there are multiple solutions and we must output smallest x. Since we test in increasing order, we will output the smallest working x.
Now, what about the possibility that the same x can be generated from multiple a_j; we deduplicate.
Now, confirm with example: Input:
3 2
0 0 0
1 1 1
a_sorted = [0,0,0], b_sorted=[1,1,1], b0=1. Candidates: (1-0)%2=1 -> set{1}. Test x=1: m-x=1, split = bisect_left([0,0,0],1) => 3. shifted = [] + [0+1,0+1,0+1] = [1,1,1] matches. Output 1.
Now, another test: maybe x=0 could also work? Not in this case.
Now, test with random to ensure correctness.
Consider n=4, m=5, a=[1,2,3,4], b=[0,1,2,3]? Let's find x: For x=4? a+4 mod5: [0,1,2,3] matches. So answer 4. b0=0. Candidates: from a: (0-1)%5=4, (0-2)%5=3, (0-3)%5=2, (0-4)%5=1 => {1,2,3,4}. Sorted:1,2,3,4. Check x=1: m-x=4, split = first a_sorted[i]>=4? a_sorted=[1,2,3,4] => index 3 (value4). wrapped: i=3 => 4+1-5=0; non-wrapped: i=0..2 => 1+1=2,2+1=3,3+1=4 => shifted = [0,2,3,4] != b_sorted [0,1,2,3]. x=2: m-x=3, split = first >=3? index 2 (value3). wrapped: i=2,3 => 3+2-5=0,4+2-5=1 => [0,1]; non-wrapped: i=0,1 => 1+2=3,2+2=4 => [3,4] => shifted=[0,1,3,4] != b_sorted. x=3: m-x=2, split= first >=2? index 1 (value2). wrapped: i=1,2,3 => 2+3-5=0,3+3-5=1,4+3-5=2 => [0,1,2]; non-wrapped: i=0 => 1+3=4 => [4] => shifted=[0,1,2,4] not match. x=4: m-x=1, split= first >=1? index 0 (value1). wrapped: all i: values: 1+4-5=0,2+4-5=1,3+4-5=2,4+4-5=3 => [0,1,2,3] matches. So answer 4. Our algorithm picks min working =4.
Now, consider scenario where x=0 also works, but candidate set includes 0. Our sorted list will have 0 first, test, if works output 0.
Thus algorithm correct.
Now, about the guarantee of existence: it says "It is guaranteed that there exists some non-negative integer x, such that it would be possible...". So we don't need to handle no-solution.
Now, we should also consider that m could be up to 1e9, but our algorithm uses only addition/subtraction, no issues.
Now, let's test more thoroughly with some tricky scenario: Suppose there are multiple a elements that after shift become the same smallest value, but our candidate generation picks x based on one of them. That's fine.
Now, what about if the smallest element in A' is from a non-wrapped element, but also there is a wrapped element that is also small? Actually the smallest element is the minimum of all (a_i + x) mod m. That could be from wrapped or non-wrapped. Our candidate generation uses b0 and any a_j. For a given working x, there exists at least one a_j such that (a_j + x) mod m = b0. So x is in candidate set. So it's fine.
Now, is there any possibility that the smallest element in A' is not b0 because b0 appears but it's not the smallest? That can't happen because b0 is smallest in B, and multisets equal, so smallest in A' must be b0.
Thus all good.
Now, one more nuance: Our candidate set is derived from b0 and each a value. But what if b0 appears multiple times and the smallest element of A' might correspond to a particular a value that yields b0, but that a value might not be present in the original a? Wait a_j is from a. Yes, it's present. So fine.
Now, double-check for correctness: Are we using b_sorted[0] as the smallest? Yes, b_sorted is sorted ascending.
Now, consider if b_sorted[0] = 0 and some a_j = 0, then candidate x=0. Could there be an x that is smaller than 0? No.
Now, final step: implement and test with given examples.
But before finalizing, let's consider if there is any scenario where our construction of shifted sorted might produce a list that is not sorted because the wrapped part might not be sorted? It is sorted because a_sorted is sorted and we add constant.
Now, potential bug: In Python, bisect_left returns the insertion point. For m-x, if m-x is greater than all a_sorted, returns n. Good. If m-x is 0? m-x > 0 always? Actually if x = m, but x < m, so m-x >=1. So fine.
Now, code skeleton:
import sys, bisect
def solve():
data = sys.stdin.read().split()
if not data: return
it = iter(data)
n = int(next(it))
m = int(next(it))
a = [int(next(it)) for _ in range(n)]
b = [int(next(it)) for _ in range(n)]
a_sorted = sorted(a)
b_sorted = sorted(b)
b0 = b_sorted[0]
candidates = set()
for val in a:
x = (b0 - val) % m
candidates.add(x)
for x in sorted(candidates):
split = bisect.bisect_left(a_sorted, m - x)
shifted = []
# wrapped
for i in range(split, n):
shifted.append(a_sorted[i] + x - m)
# non-wrapped
for i in range(split):
shifted.append(a_sorted[i] + x)
if shifted == b_sorted:
print(x)
return
if name == "main":
solve()
We should test with examples.
Example1:
4 3
0 0 2 1
2 0 1 1
a = [0,0,2,1] -> sorted [0,0,1,2]
b sorted [0,1,1,2]; b0=0.
candidates: (0-0)%3=0, (0-0)%3=0, (0-2)%3=1, (0-1)%3=2 => {0,1,2}
sorted [0,1,2]
x=0: split = bisect_left([0,0,1,2], 3) ->4 => shifted = [] + [0,0,1,2] = [0,0,1,2] != [0,1,1,2] -> fail
x=1: split = bisect_left(..., 2) -> index of first >=2 is 3 (value 2) => split=3 => wrapped: i=3 -> 2+1-3=0 => [0]; non-wrapped: i=0,1,2 -> 0+1=1,0+1=1,1+1=2 => [1,1,2] => shifted = [0,1,1,2] matches -> print 1 -> correct.
Example2: works.
Example3: works.
Now, check a scenario with large m and n=1: n=1, m=1000000000, a=[123456], b=[987654321] -> x = (b0 - a0) % m = (987654321 - 123456) % 1000000000 = 987530865? Actually compute: 987654321-123456=987530865, mod m = 987530865. candidates set {987530865}. x=987530865: split = bisect_left([123456], m - x). m-x = 1000000000-987530865 = 12469135. Since 123456 < 12469135, split=1? Actually a_sorted = [123456], bisect_left([123456], 12469135) -> 1 (since 123456 < threshold, so insertion point 1). split=1. wrapped: i from split to n-1 -> i=1? But n=1, so range(1,1) empty. Non-wrapped: i 0 to 0 -> value 123456+987530865 = 987654321? 123456+987530865 = 987654321, modulo m? But it's less than m? 987654321 < 1000000000, so yes. So shifted=[987654321], matches b_sorted [987654321]. So output 987530865. That is correct.
Now, check scenario where m-x = threshold equals exactly some a value: e.g., n=3, m=10, a=[1,4,9], x=1: m-x=9, split = first >=9? a_sorted [1,4,9] -> index 2 (value 9). We treat 9 as wrapped: value = 9+1-10=0. That's correct because (9+1)%10=0. So our algorithm includes it in wrapped, which is fine.
Now, check scenario where a has values that equal m-x, and they are considered wrapped. That yields values 0, which might be less than other wrapped? Example: a=[5,5,5] m=10, x=5 => m-x=5. split = first >=5 => index 0 (since 5>=5). So all are wrapped. shifted = [5+5-10=0,0,0] = [0,0,0]. That's correct.
Now, check scenario with duplicate values causing multiple wrapped.
Now, final check: The problem statement says "non-negative integer x". x could be 0, and we treat modulo accordingly.
Now, performance: 2000 candidates, each we iterate over n twice (two loops). That's 4 million iterations, plus bisect (log n). Very fast.
Now, confirm that we don't need to consider candidate x = (b0 - a_i) mod m but also maybe from other b elements? Because smallest element of A' is b0, so that's sufficient.
Now, some might worry about case where b0 appears multiple times, but it's fine.
Thus solution is correct.
Now, edge: n=0? Not allowed (n>=1).
Now, let's think about the possibility of overflow in Python? No.
Now, we can also avoid building shifted list if we compare directly: After split, we can compare:
- The number of wrapped elements = n - split. So first n - split elements of b_sorted should equal the wrapped values. We can compute and compare. Similarly, remaining split elements should equal non-wrapped values. This may avoid creating a new list, but it's fine.
Now, for completeness, implement direct comparison to save memory:
shifted_wrapped = [a_sorted[i] + x - m for i in range(split, n)]
if shifted_wrapped != b_sorted[:len(shifted_wrapped)]: continue
shifted_nonwrapped = [a_sorted[i] + x for i in range(0, split)]
if shifted_nonwrapped != b_sorted[len(shifted_wrapped):]: continue
But note: b_sorted is sorted, and our construction yields sorted list. This comparison is fine. However, we need to ensure that the concatenation is exactly b_sorted. We can just compare slices. This avoids concatenation. But not necessary.
We can also do one pass: iterate i from split to n-1, compute val and compare with b_sorted[j] incrementally; then from 0 to split-1.
I'll implement direct comparison to be efficient and avoid extra list creation:
def check(x):
split = bisect.bisect_left(a_sorted, m - x)
idx = 0
# wrapped part
for i in range(split, n):
if a_sorted[i] + x - m != b_sorted[idx]:
return False
idx += 1
# non-wrapped part
for i in range(split):
if a_sorted[i] + x != b_sorted[idx]:
return False
idx += 1
return True
Then for each candidate x in sorted list, if check(x): print(x); return.
This avoids building a new list and is O(n) per x.
Now, we must consider that b_sorted length is n, and we iterate exactly n times.
Implementation:
import sys, bisect
def main():
import sys, bisect
input_data = sys.stdin.read().split()
if not input_data:
return
it = iter(input_data)
n = int(next(it))
m = int(next(it))
a = [int(next(it)) for _ in range(n)]
b = [int(next(it)) for _ in range(n)]
a_sorted = sorted(a)
b_sorted = sorted(b)
b0 = b_sorted[0]
candidates = set()
for val in a:
candidates.add((b0 - val) % m)
for x in sorted(candidates):
split = bisect.bisect_left(a_sorted, m - x)
# verify
ok = True
idx = 0
# wrapped
for i in range(split, n):
if a_sorted[i] + x - m != b_sorted[idx]:
ok = False
break
idx += 1
if ok:
for i in range(split):
if a_sorted[i] + x != b_sorted[idx]:
ok = False
break
idx += 1
if ok:
print(x)
return
if name == "main":
main()
Test with examples.
Now, consider the case where split = n: then first loop (wrapped) range(n, n) empty, idx stays 0, then second loop for i in range(n) compares a_sorted[i] + x with b_sorted[idx], which works. Good.
If split = 0: first loop runs for i in range(0,n) does wrapped comparisons; second loop empty. Good.
Now, careful: When split=0, we compute a_sorted[i] + x - m. That must equal b_sorted[idx]. It should work if x is valid.
Now, we must ensure that we handle the case where m-x could be zero? Not possible because x < m, so m-x >= 1. However, if m=1, then x can be 0, m-x=1, okay. If m=1 and x=0, fine.
Now, test with m=1, n=1, a=[0], b=[0]. candidates: b0=0, (0-0)%1=0. x=0. split = bisect_left([0], 1) -> 1 (since 0<1). split=1. First loop empty. second loop i from 0 to 0: a_sorted[0]+0=0, compare with b_sorted[0]=0 => ok. Output 0.
All good.
Now, think about potential issues with using set of candidates and then sorting. Sorting candidates may produce order like [0,1,2,...]. That's fine.
Now, could there be a case where the correct x is not in the candidate set because the smallest element in A' is not b_sorted[0] due to tie-breaking? But even if there are ties, the smallest value is still b_sorted[0]. So it's fine.
Now, consider the scenario where b_sorted[0] appears, but the smallest element in A' could be something less than b_sorted[0] if the multiset didn't match? No.
Thus solution stands.
Now, we should consider the scenario where n=2000, but m is huge, and candidate x are many (2000). Our check is O(n) each, fine.
Now, let's double-check the correctness of the check: In the wrapped part, we compute a_sorted[i] + x - m. Since a_sorted[i] >= m - x, this value is >=0. And we compare with b_sorted[idx] which is sorted. Since wrapped values are all less than non-wrapped values, and b_sorted is sorted, it's correct.
But is it always true that the wrapped part corresponds exactly to the first (n-split) elements of b_sorted? Yes, because in sorted A', wrapped values come first. So the first n-split entries of sorted A' are the wrapped ones, and these should match the first n-split entries of sorted B. So our comparison order is correct: we first compare wrapped values in order with the start of b_sorted.
Now, consider the scenario where there are no wrapped values (split=n). Then we compare only non-wrapped values with b_sorted from start. That's fine.
Now, consider the scenario where all values are wrapped (split=0). Then we compare wrapped values with b_sorted from start. That's fine.
Now, check that we are using the same order as in the sorted A' construction. For split>0, wrapped indices are from split to n-1. The values are a_sorted[i] + x - m. Since a_sorted[i] increasing, these values are increasing (because adding constant x-m). So they are in ascending order. So they correspond to the smallest values. Good.
Now, note: Could there be a case where wrapped part has values that are not strictly less than non-wrapped? We argued earlier it's always less. But let's double-check with an example: m=5, x=3, so m-x=2. Suppose a_sorted = [0,4]. Check: split = first >=2? a_sorted: 0<2, 4>=2 -> split=1 (only index1). Wrapped: i=1 => 4+3-5=2. Non-wrapped: i=0 => 0+3=3. So wrapped=2, non-wrapped=3, indeed 2<3. So works.
What if a_sorted = [1,4]? split: first >=2? 1<2, 4>=2 -> split=1. Wrapped: 4+3-5=2, non-wrapped: 1+3=4 => 2<4.
Now, consider x=0, no wrapped.
Thus always true.
Now, confirm that when we compute (b0 - val) % m, we use Python's modulo which yields non-negative result. Good.
Now, we might need to handle large input reading efficiently. Using sys.stdin.read().split() is fine.
Now, final answer.
But before finalizing, let's think about any hidden pitfall: The problem statement says "increase all elements of a_i by x, modulo m (i.e. you want to change a_i to (a_i + x) mod m)". So it's a shift mod m.
Our method uses (a_i + x) mod m. In our construction, we treat (a_i + x) mod m as either a_i + x if a_i + x < m, else a_i + x - m. That's correct.
Now, what about using negative x? We only consider non-negative x.
Now, all good.
Let's also test with random brute-force for small n,m to ensure algorithm matches brute force. We could do mental or maybe write a test, but in analysis we can trust.
Now, potential bug: using b0 = b_sorted[0] is fine, but what if there are multiple b elements that are equal? That's fine.
But consider scenario where after shift, the smallest element of A' is not b0 because b0 is the smallest in B but there might be a smaller element in A' due to wrap? That would mean multisets not equal, so x not valid. So for valid x, it's not an issue.
Now, one more nuance: The candidate generation uses b0. But what if b0 appears multiple times and the smallest element in A' also appears multiple times, but the number of occurrences of b0 in B might be different from the number of a_j that map to b0? That's fine; the x must satisfy that the multiset matches, so the count of b0 in B must equal the count of (a_i + x) mod m equal to b0. In our candidate generation, we don't consider counts; we just generate x from each a_j. So if there is an x that works, there is at least one a_j that maps to b0, so x will be generated from that a_j. So it's in set.
Now, could there be a scenario where no a_j maps to b0 but the multiset still matches? That would mean b0 is not in the image of the shifted a, contradicting that multisets are equal. So impossible.
Thus safe.
Now, finalize.
But wait, there is a subtle point: The candidate x is computed as (b0 - a_j) mod m. However, what if b0 is from B sorted, but after shift, the smallest element in A' might be b0, but there might be an element a_k such that (a_k + x) mod m = b0 but also there is another element a_l such that (a_l + x) mod m also equals b0? That's okay. The candidate will be generated from both a_k and a_l, but same x.
Now, think about the possibility that our check may incorrectly reject a valid x because of ordering of the two segments? Our ordering assumes wrapped values are first. Could there be a valid x where after shift, the smallest element in A' is b0, but the sorted order of A' does not necessarily have all wrapped values first? Actually we argued that's always the case. However, is it possible that some wrapped value is greater than some non-wrapped value? Let's check the condition: wrapped: a_i >= m - x, value = a_i + x - m. Non-wrapped: a_j < m - x, value = a_j + x. We want to compare a_i + x - m with a_j + x. Since a_i >= m - x and a_j < m - x, we have a_i >= m - x > a_j. Then a_i + x - m >= 0, a_j + x < m. But we need to compare sizes: a_i + x - m vs a_j + x. Subtract: (a_i + x - m) - (a_j + x) = a_i - a_j - m. Since a_i - a_j < m? Actually a_i <= m-1, a_j >=0, so a_i - a_j <= m-1. Then (a_i - a_j - m) <= -1. So it's negative: a_i + x - m < a_j + x. So indeed wrapped values are less than non-wrapped. So ordering holds.
Thus no issue.
Now, double-check the subtract: (a_i - a_j - m) <= (m-1 - 0 - m) = -1, so it's ≤ -1. So indeed wrapped < non-wrapped. So ordering is strict. So sorted A' = wrapped part (increasing) concatenated with non-wrapped part (increasing) yields the sorted list.
Thus check is correct.
Now, final implementation.
Potential minor optimization: We can precompute a_sorted and b_sorted.
Now, I'll produce final answer.
But we need to ensure we import bisect.
Now, confirm for large m and n, performance okay.
Now, I think it's correct.
Let's test with a scenario where there is more than one candidate and we need smallest.
Example: n=4, m=10, a=[0,1,2,3], b=[3,4,5,6]? Let's find x. Possibly x=3 gives shifted=[3,4,5,6] matches. b0=3. Candidates: (3-0)%10=3, (3-1)%10=2, (3-2)%10=1, (3-3)%10=0. So candidates {0,1,2,3}. Check x=0: shifted=[0,1,2,3] vs b_sorted [3,4,5,6] fail. x=1: shifted=[1,2,3,4] vs [3,4,5,6] fail. x=2: shifted=[2,3,4,5] vs fail. x=3: works. So answer 3.
Now, if we test in ascending order, we find at x=3.
Now, what if x=2 also works? Not in this case.
Now, one more test: duplicate values in a and b. For instance, a=[0,0,1,1], m=5, b=[1,1,2,2]? Choose x=1: shifted=[1,1,2,2] matches. b0=1. Candidates: (1-0)%5=1, (1-0)=1, (1-1)=0, (1-1)=0 => {0,1}. x=0: shifted=[0,0,1,1] vs [1,1,2,2] fail. x=1: works. So answer 1.
Now, a scenario where answer is 0: already tested.
Now, check scenario where answer is large close to m-1, but we have candidate. It's fine.
Now, think about the possibility that the smallest valid x is not the smallest candidate but a larger one? Since we test candidates in increasing order, the first one that passes is the smallest valid. That's correct.
Now, consider scenario where there is a candidate x that is smaller than the true answer but fails. Then we test it and reject, then later test the true answer and accept. So correct.
Now, any possibility that the candidate list does not include the true answer? We already argued it does.
But wait: The candidate generation uses b0, the smallest element of B. However, could it be that for the correct x, the smallest element of A' is indeed b0, but that b0 is achieved by some a_j, but that a_j is not present in the original a? That's impossible because a_j is from a.
So fine.
Now, finalize.
But I recall a similar Codeforces problem "Make Them Equal" where the solution is exactly this: sort arrays, then try each x = (b[0] - a[i]) mod m, check by constructing array as described. Yes, it's known.
Now, one more nuance: The problem statement says "increase all elements of a_i by x, modulo m (i.e. you want to change a_i to (a_i + x) mod m)". So it's a global shift. So the approach is correct.
Now, writing final solution.
We should also consider using fast IO.
Now, final code:
import sys, bisect
def solve():
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
m = int(next(it))
a = [int(next(it)) for _ in range(n)]
b = [int(next(it)) for _ in range(n)]
a.sort()
b.sort()
b0 = b[0]
cand = set()
for val in a:
cand.add((b0 - val) % m)
for x in sorted(cand):
split = bisect.bisect_left(a, m - x) # a is now sorted
ok = True
idx = 0
for i in range(split, n):
if a[i] + x - m != b[idx]:
ok = False
break
idx += 1
if ok:
for i in range(split):
if a[i] + x != b[idx]:
ok = False
break
idx += 1
if ok:
print(x)
return
if name == "main":
solve()
Now, test with given examples.
We need to be careful: after a.sort(), a is sorted. We use it for both candidate generation and later checks. For candidate generation we used original a before sorting? Actually we used a after sorting? In above code, we did a.sort() then used a in the loop. But candidate generation uses the values from a (which are now sorted). That's fine because set of values is same. But careful: When we read a, we store in list a. Then we sort it. That modifies a. Then we iterate over a to generate candidates. That's okay because we only need the values; sorted order doesn't matter. So fine.
But we also need original unsorted? Not for checking. So it's fine.
Now, I used sys.stdin.buffer.read().split() for faster reading.
Now, we need to convert bytes to int: when iterating, next(it) returns bytes, int() works with bytes? In Python, int(b'123') works? Actually int(b'123') works: int(b'123') returns 123. So fine.
But be safe: In Python 3, int() can take bytes. Good.
Alternatively, we could decode, but it's fine.
Now, final answer.
Now, confirm with example 1.
We'll run mental simulation:
data: "4 3 0 0 2 1 2 0 1 1"
n=4,m=3
a = [0,0,2,1] -> sort -> [0,0,1,2]
b = [2,0,1,1] -> sort -> [0,1,1,2], b0=0
cand: for val in a: (0-0)%3=0, (0-0)=0, (0-1)%3=2, (0-2)%3=1 -> set {0,1,2}. sorted -> [0,1,2]
x=0: split = bisect_left([0,0,1,2], 3) -> 4. loop1: range(4,4) none; idx=0; loop2: i=0: a[0]+0=0 vs b[0]=0 ok; i=1:0 vs b[1]=1? fails -> ok=False. So x=0 fails.
x=1: split = bisect_left([0,0,1,2], 2) -> first >=2? a[3]=2 so split=3. loop1: i=3: a[3]+1-3=0 vs b[0]=0 ok idx=1; loop2: i=0:0+1=1 vs b[1]=1 ok idx=2; i=1:0+1=1 vs b[2]=1 ok idx=3; i=2:1+1=2 vs b[3]=2 ok. So ok=True, print 1. Done.
Works.
Now, potential bug: In loop2 we start from split, but after first loop idx may have been incremented. That's correct.
Now, also note that we used a for sorted a. In the second loop we use range(split). Good.
Now, note: In the check, we used a[i] + x - m. Since a[i] >= m - x for wrapped indices, this is non-negative. But in Python, it's fine.
Now, final code is ready.
Now, we can also think about the case where m - x is exactly equal to some a value. As discussed, that a is considered wrapped.
Now, I think we can finalize.
But wait, one more nuance: In the problem statement, they said "you need to find the smallest non-negative integer x". So we should output x as integer.
Now, final answer: Provide the code.
But the user asked: "You are given ... Output ..." So the answer should be the integer output. In typical interaction, we just output the integer. So our code prints it.
Now, confirm with additional random test: n=2, m=100, a=[99,0], b=[0,1]? Does there exist x? Suppose x=1: (99+1)%100=0, (0+1)=1 => b = [0,1] works. So answer 1. b_sorted [0,1], b0=0. Candidates: (0-99)%100=1, (0-0)%100=0 -> {0,1}. x=0: split=bisect_left([0,99],100)=2 => shifted = [0,99] vs b_sorted [0,1] fails. x=1: split=bisect_left([0,99],99) because m-x=99? Actually m-x=99, split = first >=99? a_sorted [0,99] => index1 (value 99). Then wrapped: i=1: 99+1-100=0; non-wrapped: i=0: 0+1=1 => shifted sorted = [0,1] matches. So answer 1. Good.
Now, what about scenario where there are multiple valid x, and the smallest is not from the candidate set? Already argued impossible.
Now, one more scenario: Could the candidate set be missing the smallest x if the smallest x leads to the smallest element of A' being something else but still multisets equal? That would contradict that multisets equal because sorted lists would have different smallest element. So impossible.
Thus solution correct.
Now, I'll produce final answer with explanation.
But the user may be expecting just the code? The instruction: "You are an AI assistant that solves competitive programming problems. Provide the final answer in the format: a code block with the solution." So we need to output code.
Thus final answer: Provide Python solution.
Now, I'll write a thorough explanation in the response? The user says: "You are an AI assistant that solves competitive programming problems. Provide the final answer in the format: a code block with the solution." So we need to output only the code? Typically, we provide solution description plus code. But instruction says final answer in code block. I'll include code block.
But as ChatGPT, I can also include brief explanation. But the problem statement likely expects just code. However, the prompt: "You are an AI assistant that solves competitive programming problems. Provide the final answer in the format: a code block with the solution." So I'll output a code block with the Python code.
I'll also include import and main guard.
Now, I'll present final code:
import sys
import bisect
def main():
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
m = int(next(it))
a = [int(next(it)) for _ in range(n)]
b = [int(next(it)) for _ in range(n)]
a.sort()
b.sort()
b0 = b[0]
cand = set()
for val in a:
cand.add((b0 - val) % m)
for x in sorted(cand):
split = bisect.bisect_left(a, m - x)
ok = True
idx = 0
# wrapped part (values < x)
for i in range(split, n):
if a[i] + x - m != b[idx]:
ok = False
break
idx += 1
if ok:
# non-wrapped part (values >= x)
for i in range(split):
if a[i] + x != b[idx]:
ok = False
break
idx += 1
if ok:
print(x)
return
if __name__ == "__main__":
main()
Now, this is the final solution.
But wait: There's a subtle bug: In the first loop, we use a[i] + x - m. But a[i] could be less than m-x? No, because i >= split ensures a[i] >= m - x (by definition of split). So a[i] + x - m >= 0. Good.
Now, check: For x such that split may be 0, first loop covers all i. Then second loop is empty. That's fine.
Now, done.
Now, ensure that we used a after sorting, and we also used a for candidate generation. That's fine.
Now, final answer.
One more test: n=1,m=1,a=[0],b=[0] -> a.sort=[0], b.sort=[0], b0=0, cand={(0-0)%1=0}, x=0, split=bisect_left([0],1)=1, first loop empty, second loop i=0: a[0]+0=0 vs b[0]=0 ok -> prints 0.
Now, a test: n=2,m=2,a=[0,1],b=[0,1] -> x=0 works. cand: (0-0)%2=0, (0-1)%2=1 -> {0,1}. Test x=0: split=bisect_left([0,1],2)=2, second loop: i=0->0 vs b[0]=0 ok, i=1->1 vs b[1]=1 ok. Prints 0.
Now, test: n=2,m=2,a=[0,1],b=[1,0]? But sorted b = [0,1] same as above, x=0 works? Actually if we can rearrange, yes. So answer 0.
Now, test: a=[0,1], b=[0,0]? Not possible, but guarantee says exists.
Thus code should pass.
Now, finalize. ```python
import sys
import bisect
def main():
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
m = int(next(it))
a = [int(next(it)) for _ in range(n)]
b = [int(next(it)) for _ in range(n)]
a.sort()
b.sort()
b0 = b[0]
# All candidate shifts: (b0 - a_i) mod m
cand = set()
for val in a:
cand.add((b0 - val) % m)
for x in sorted(cand):
split = bisect.bisect_left(a, m - x) # first index with a[i] >= m-x
ok = True
idx = 0
# Wrapped part (small values)
for i in range(split, n):
if a[i] + x - m != b[idx]:
ok = False
break
idx += 1
if ok:
# Non-wrapped part (larger values)
for i in range(split):
if a[i] + x != b[idx]:
ok = False
break
idx += 1
if ok:
print(x)
return
if name == "main":
main()