We need to solve problem: given array of n numbers (n >= 3), we need to rearrange them so that the absolute differences between consecutive elements are non-decreasing. That is, we want a permutation b[1..n] of a such that:
|b[1]-b[2]| <= |b[2]-b[3]| <= ... <= |b[n-1]-b[n]|.
We can output any such permutation. Guaranteed always possible.
We need to handle up to 1e5 total n.
Observation: The condition is like we want the differences to be increasing (or non-decreasing). Typically one might think of sorting the array and then arranging to have differences increasing. But after sorting, the differences between adjacent sorted elements are usually varying, but they are not necessarily monotonic. For example, sorted: [1,2,4,8] gives differences 1,2,4 which is increasing. Actually that works. But if there are duplicates or larger variations? For sorted array, differences are not guaranteed to be monotonic? Actually if array is sorted ascending, differences are between consecutive sorted values: they could be like 5,1,3... Not sorted? Wait sorting ensures a_i <= a_{i+1}, but the differences are nonnegative; however the sequence of differences is not necessarily non-decreasing; it could fluctuate. Example: [1,3,4,9] differences: 2,1,5 => not monotonic. So we need to rearrange.
But maybe we can design a construction. The guarantee says "It's always possible to find such rearrangement". So there is always some permutation. We need to produce one quickly.
We can think of constructing a sequence where differences increase. One typical trick: take the sorted array, then pick the smallest and largest and interlace? Or something like "mountains"? Let's explore.
We need |b1-b2| <= |b2-b3| <= ... . So the early differences should be small, later differences large. So we want early consecutive numbers close together, later far apart.
Idea: Sort the array. Then take the smallest difference? But we have to place numbers so that the absolute differences gradually increase.
One construction: Place the numbers in a "zigzag" pattern: first the median, then the extremes? Actually maybe we can arrange them such that the differences are like: between two numbers that are close, then between one of them and a far number yields a large difference, but we need monotonic increase.
Consider an array sorted: x1 <= x2 <= ... <= xn. Then we can produce sequence: x1, xn, x2, x_{n-1}, x3, ...? Let's test: differences: |x1 - xn| (large), then |xn - x2| (maybe also large but could be smaller? Actually |xn - x2| is near the max, maybe smaller than |x1-xn|? Example: [1,2,4,8]: x1=1,xn=8,x2=2,x3=4? Sequence: 1,8,2,4. Compute diffs: |1-8|=7, |8-2|=6 (decreasing) not good. So not that.
Maybe we can arrange in order of values but starting from one end and then moving to the other, but ensuring that differences are increasing. For differences to increase, we want the consecutive pairs to get farther apart. So perhaps we can start with two numbers that are close (maybe duplicates or near), then gradually bring in numbers that are far from the previous ones, creating larger differences.
One approach: Choose an order where we first list numbers that are close together, then eventually jump to extremes. But we need monotonic increase, so each step must produce a difference at least as large as the previous.
We could think of constructing the sequence backwards: start with a pair that has largest possible difference, then prepend numbers that create smaller differences before it. Because if we build from the end, we want the last difference to be the largest, and then earlier differences smaller.
Specifically, we want |b_{n-1} - b_n| to be the maximum difference among consecutive pairs. So we could set b_{n-1} and b_n to be the two numbers that are farthest apart (min and max). That yields largest possible difference: D = max - min. Then we need to place the remaining numbers before b_{n-1} such that the preceding differences are <= D and non-decreasing. Could we then set b_{n-2} such that |b_{n-2} - b_{n-1}| is also large but <= D? But we have already used min and max. The next large difference could be between min and second max or max and second min. But we need a chain of differences increasing. Perhaps we can set the entire sequence as a path that starts at some point and then each step moves to a point further away, eventually reaching the farthest. This is reminiscent of constructing a sequence by repeatedly taking the farthest point from the current one? But we need monotonic increase of step sizes, not necessarily the step sizes themselves; they must be non-decreasing, so we could have repeated same size.
Alternative: Since we can output any arrangement, maybe we can always sort the array and then output it except maybe some transformation that ensures differences are non-decreasing? Could we simply sort and then compute differences, then reorder based on those differences? Not straightforward.
Maybe we can note that the condition is equivalent to the sequence of absolute differences being sorted. So we need to assign the numbers to positions such that the absolute differences between consecutive numbers form a non-decreasing sequence. So we have to choose an ordering.
This problem appears to be from Codeforces (I think problem 1506C? Actually maybe from 2021? Let me recall: There's a known problem: "Absolute differences sorting" where you need to arrange numbers so that the absolute differences between consecutive elements are non-decreasing. The typical solution: sort the array, then split into two halves: lower half and upper half, then interlace them in a particular way. Let's test: Suppose n=6 sorted: L = [x1,x2,x3] (small), R = [x4,x5,x6] (large). Then order: x1, x4, x2, x5, x3, x6. Differences: |x1-x4|, |x4-x2|, |x2-x5|, |x5-x3|, |x3-x6|. Not obviously monotonic. But maybe with careful selection of how to split? Alternatively, I've seen a known construction: If you put all numbers in sorted order and then take the median as start, then go to the extremes? Actually think: Suppose we take the smallest element, then the largest, then the second smallest, then second largest, ...? That yields differences: small-large (large), large-second small (maybe smaller), etc. Not monotonic.
Maybe we can produce a sequence that is "V-shaped": start from one end, go to the other, and then back? But we have only one direction.
Wait, maybe the condition is that the absolute differences are non-decreasing, which means the "step sizes" increase. So we could think of constructing a path where each step size is at least the previous. This is similar to the idea of constructing a "growing walk" on the real line using given points. Given a multiset of points on the line, we need to order them such that the distances between consecutive points are non-decreasing. This is always possible? The guarantee says yes.
Let's try to think constructively: Suppose we have sorted list. Pick the smallest element as start. Then we need to choose next element such that the difference d1 is minimal possible among remaining pairs? But then subsequent differences must be >= d1. So maybe we want d1 as small as possible. The smallest possible absolute difference between any two distinct numbers? If there are duplicates, we can set d1=0 using two equal numbers. So we can start with a duplicate pair if exists.
But after we choose first pair, we have remaining points. We need to add more points to the sequence, extending either from left or right? Because the sequence is linear; we can only add to the end? Actually we are constructing the whole permutation; we can decide order arbitrarily. So we could build the sequence by starting with two numbers that are close, and then repeatedly attach a number to either the front or the back of the current sequence? Wait we need a linear order b1..bn. If we construct by starting with a segment (b_i...b_j) and then extend at ends, we could build the full sequence. Because if we have a current sequence from L to R (positions 1..k), we can only add elements at the ends? Actually when constructing, we can place numbers anywhere, but if we think of building the sequence from scratch, we can insert numbers between existing ones? No, that would break order. However, we can think of building the sequence by starting with two numbers that yield the smallest difference, and then adding new numbers to either the leftmost or rightmost end such that the new difference (between new element and current end) is at least the previous largest difference? But the condition requires that all differences are non-decreasing when read from left to right. If we build by extending at the ends, we need to ensure that when we add to the left, the difference between new leftmost and the old leftmost becomes the new first difference. That difference must be <= the second difference (which was originally first). That could be a constraint.
Alternatively, we could construct the sequence in reverse: start with the largest difference (the endpoints of the whole set: min and max). Then insert numbers between them, ensuring that the inserted gaps are smaller and sorted. That is like taking the sorted list and then placing numbers in some order that yields increasing gaps. Possibly we can take the sorted array and then output it in a specific permutation: e.g., take the median, then one of the extremes, then the other median? Hmm.
Let's try to solve for small n to see patterns.
n=3: We need |b1-b2| <= |b2-b3|. Given any three numbers, can we always arrange? Let's check. Suppose numbers are a,b,c. We need to order them so that the smaller difference is first. Is it always possible? Intuitively, yes. For three numbers, we can sort them: x <= y <= z. Differences: y-x and z-y. They could be any. We need to assign them to b1,b2,b3 such that first diff <= second diff. If y-x <= z-y, then order x,y,z works. If z-y < y-x, then we can use order z,y,x? Check: |z-y| = z-y, |y-x| = y-x. Since z-y < y-x, then we have smaller first: z,y,x works because first diff = z-y, second = y-x, and z-y <= y-x? Actually if z-y < y-x, then indeed we have first diff smaller. So either sorted ascending or descending works depending on which gap is larger. More systematically: we can pick the two numbers that are closest together as the first pair, and the remaining as third. So for n=3, it's easy.
For larger n, we can think recursively: after fixing the first two numbers, we need to place remaining n-2 numbers in order such that the differences from b2 onward satisfy the condition for the tail. But that's like a subproblem with the first element fixed? Actually if we have b1 and b2 already, we need to choose b3...bn such that |b2-b3| <= ... <= |b_{n-1}-b_n| and also |b1-b2| <= |b2-b3|. So we need the tail's first difference at least d1. So we need to construct a sequence starting from b2 where the differences are non-decreasing and the first difference is at least d1. This suggests a greedy approach: sort numbers, then perhaps we can arrange them such that the differences are like the sorted list of all pairwise differences? Not exactly.
Another angle: Since the condition only cares about absolute differences, we can think of the numbers as points on the number line. We need to traverse them in some order such that the step sizes are non-decreasing. This is reminiscent of the "greedy algorithm" for the traveling salesman problem with increasing steps? Not sure.
Maybe there's known result: For any multiset of real numbers, there exists a permutation such that the absolute differences are non-decreasing. This is similar to the concept of "universal sorted differences". One known construction: sort the array, then take the smallest, then the largest, then the second smallest, then the second largest, ...? Already tested fails. Another: sort, then take the median, then the left neighbor, then right neighbor, then left-left, etc. That is like "alternating around median". For sorted a1 <= a2 <= ... <= an. Consider sequence: a_{(n+1)/2}, a_{(n+1)/2 -1}, a_{(n+1)/2 +1}, a_{(n+1)/2 -2}, ... This is like starting from median and expanding outward. Let's test with [1,2,4,8] (median maybe 2? Actually n=4, median between 2 and 3: a2=2, a3=4. If we start from a2=2, then left neighbor a1=1, then right neighbor a3=4, then left? but we have a4=8? Let's try order: 2,1,4,8. Differences: |2-1|=1, |1-4|=3, |4-8|=4 => 1<=3<=4 works! Nice. What about starting from a3=4: 4,2,1,8? |4-2|=2, |2-1|=1, 1<2? Actually 2<=1 false. Not good. So maybe we need to pick the median and then go to the smaller neighbor first? Let's test with other arrays.
Test [1,3,4,9] sorted: 1,3,4,9. Median (n/2?) For even n, maybe take the larger of the two medians? Let's try starting from a2=3? Sequence: 3,1,4,9. Differences: |3-1|=2, |1-4|=3, |4-9|=5 => 2<=3<=5 works! Starting from a3=4? 4,3,1,9: |4-3|=1, |3-1|=2, |1-9|=8 => 1<=2<=8 works! Actually both seem to work? Check: 4,3,1,9 yields differences: 1,2,8 -> good. 3,1,4,9 yields 2,3,5 -> good. But are there cases where it fails? Try [1,5,10,11] sorted: 1,5,10,11. Try median maybe a2=5: order 5,1,10,11 => diffs: 4,9,1 -> 4<=9 yes, 9<=1 no. That fails because last diff 1 is smaller. So 5,1,10,11 fails because after 1 to 10 diff 9, then 10 to 11 diff 1 which is less than 9. So need to ensure that the last step is large enough. In our sequence, we went from 10 to 11 which is small. So maybe we need to end with an extreme? In the successful examples above, the final element was the largest (9, 9, 8?) In [1,3,4,9] we ended with 9, so last diff 4->9 =5, which is large. In [1,2,4,8] we ended with 8, diff 4->8=4. So maybe we should always start from some point and then alternate left-right but ensure that the final element is either min or max? In the failing case [1,5,10,11], if we start with median around 5 or 10? Let's try start with 10: 10,5,1,11? diffs:5,4,10 -> 5<=4 false. 10,5,11,1? That's different order not following simple alternating. Let's think systematic.
We have sorted array x1 <= x2 <= ... <= xn.
Consider constructing sequence by taking elements from the ends alternating, but perhaps starting from one of the ends? Example: x1, xn, x2, x_{n-1}, x3, ... This gave first diff large, then maybe smaller. Not good.
What about: x1, x2, xn, x3, x_{n-1}, x4, ...? Let's test with [1,5,10,11]: x1=1, x2=5, xn=11, x3=10. Sequence: 1,5,11,10. diffs:4,6,1 -> fails.
What about: x1, xn, x_{n-1}, x2, x3, ...? Unlikely.
Maybe we need to arrange such that the differences are increasing, essentially we want to list numbers in order of "distance" from some starting point, but also the jumps increase.
Idea: If we take the sorted array and then reverse the second half? Not sure.
Let's attempt to design algorithm based on the concept of "mountain" or "valley". Another known Codeforces problem: "Rearrange Array so that Absolute Differences Are Non-Decreasing" (maybe problem 1730B? I'm not sure). I recall a solution: sort array, then output in order: a[1], a[n], a[2], a[n-1], a[3], ...? Wait that gave big first diff. But there is also a known trick: If we output sorted array and then rotate? Actually example output: For test1, they gave "5 5 4 6 8 -2". Let's sort the input: [-2,4,5,5,6,8] sorted. Their output: 5,5,4,6,8,-2. That's not sorted. Let's examine: They start with 5 (which is a middle value), then another 5 (duplicate), then 4 (smaller), then 6 (larger), then 8 (larger), then -2 (smallest). Differences: 0,1,2,2,10. That is non-decreasing. So they used duplicates to get 0 diff, then small diff 1 between 5 and 4, then 2 between 4 and 6, then 2 between 6 and 8, then large 10 between 8 and -2. So they placed -2 at the end, which is far from 8. So the sequence essentially goes: middle, duplicate (close), then a step down to 4, then up to 6, up to 8, then down to -2 (big jump). It's like they placed the smallest at the end. This suggests a construction: after sorting, take the second largest? Hmm.
Let's attempt to derive a general constructive algorithm.
We need to produce b1..bn. Let sorted be s1 <= s2 <= ... <= sn.
Observations:
-
The maximum possible absolute difference is sn - s1. That should be the last difference (largest) if we want monotonic. So we can set b_{n-1} and b_n to be s1 and sn (or any pair achieving max difference). But in the example, last pair is 8 and -2, which are the max (8) and min (-2). Yes, that's max difference = 10. So they made the last difference the maximum.
-
The smallest difference could be 0 if duplicates exist, else the minimum gap between any two numbers. We can arrange to have the first difference as the smallest possible. In example, first diff 0 from duplicate 5,5.
-
Then the remaining differences should be increasing from smallest to largest.
Thus, one approach: Use the min and max at the end, and then arrange the rest in between such that differences are sorted. But how to arrange the middle numbers? Perhaps we can take the remaining numbers (excluding one of the min and max) and recursively construct a sequence that ends at the other extreme? Wait, if we set b_n = sn (largest) and b_{n-1} = s1 (smallest) then last diff = sn - s1. Then we need to place the other n-2 numbers before b_{n-1} (i.e., as b1..b_{n-2}) such that the final difference of that prefix (i.e., |b_{n-2} - b_{n-1}|) is <= sn - s1 and also the entire prefix's differences are non-decreasing and end at b_{n-1} = s1. That seems like we need a sequence that ends at s1 and its last step (the difference between b_{n-2} and s1) is some value d_{n-2} <= sn-s1. Since we want monotonic increasing, we want d_{n-2} to be as large as possible but <= sn-s1. Perhaps we can set b_{n-2} = sn? But sn is already used at b_n. Not allowed. So maybe we set b_{n-2} = s_{n-1}? Then difference |s_{n-1} - s1| might be less than sn-s1, which is okay. Then we need to construct a sequence that ends at s_{n-1}? Actually b_{n-1}=s1, b_{n}=sn. But then b_{n-2} could be sn? no. We could also set b_{n-1}=sn and b_n=s1 (swap), still max diff. In example, b5=8, b6=-2, so b_{n-1}=8, b_n=-2, so max diff last. So they ended with the smallest as last. So they put sn (8) as b5, and s1 (-2) as b6. So the order before that leads to 8, then -2.
So they constructed a sequence that ends with a large number (8) and then appends the smallest at the end to get a huge final jump. So b_{n-1} is not necessarily an extreme; b_n is the extreme opposite. In this case b_{n-1}=8 (largest), b_n=-2 (smallest). The last difference is huge.
Thus, a general plan: We can aim to have the last step be the maximum difference. To achieve that, we can take one extreme as the second last element, and the opposite extreme as the last element. So we can set b_{n-1} = sn (largest) and b_n = s1 (smallest), or vice versa (b_{n-1}=s1, b_n=sn). Both give max diff.
Now, we need to arrange the first n-2 elements so that the sequence of differences up to b_{n-1} is non-decreasing and all <= max diff, and also the final step from b_{n-2} to b_{n-1} is <= max diff.
So we need to construct a permutation of the remaining numbers (the set S = {s2,..., s_{n-1}} plus maybe one of the extremes if we use both extremes? Actually we used both s1 and sn, so remaining are s2...s_{n-1}) of length n-2, that ends at b_{n-1} (which is either s1 or sn). In the example, b_{n-1}=8 (sn), and remaining numbers were {5,5,4,6}? Actually original numbers: 5,5,4,6,8,-2. Sorted: -2,4,5,5,6,8. They used sn=8 as b5, s1=-2 as b6. Remaining were {4,5,5,6}. Their sequence b1..b4: 5,5,4,6. And b5=8. So the prefix ends at 8. So they constructed a sequence of length 4 from the set {4,5,5,6} that ends at 8? Wait 8 is not in the remaining set, it's already used as b5. Actually the prefix b1..b4 uses numbers from remaining set? b1=5, b2=5, b3=4, b4=6. That's exactly the remaining numbers: {4,5,5,6}. So the prefix ends at b4=6, not 8. Then b5=8, which is an extreme not used before. So b4=6 to b5=8 diff=2, which is <= last diff 10. And the prefix differences: 0 (5-5), 1 (5-4), 2 (4-6). Those are 0,1,2 non-decreasing. Then 2 (6-8) same as previous 2, and finally 10. So it's consistent.
Thus, their construction:
- Sort the array.
- Take the maximum (sn) and put it as the second last element (b_{n-1}).
- Take the minimum (s1) and put it as the last element (b_n).
- For the first n-2 elements, they need to be arranged such that the differences are non-decreasing and the final difference from b_{n-2} to b_{n-1} is <= sn-s1.
- In the example, they arranged the remaining numbers (s2...s_{n-1}) in some order that yields non-decreasing differences and ends with a number close to sn (maybe the largest among remaining) so that the step to sn is not too large? Actually they ended with 6, which is the second largest among remaining. The step from 6 to 8 is 2, which is equal to the previous diff (2). So the last prefix diff is 2.
Thus, the problem reduces to: given the sorted list of numbers (excluding the extremes), can we arrange them in any order such that the absolute differences between consecutive numbers are non-decreasing, and also the final element of this arrangement (call it last_pre) has a difference to sn (or s1) that is >= the last diff of the prefix? Actually we need overall non-decreasing, so if the prefix's last diff is d, then we need d <= |last_pre - sn| (which is the next diff). So as long as we can make |last_pre - sn| >= d, we are good. Since sn is the largest, if last_pre is not the largest, then |last_pre - sn| = sn - last_pre. To maximize this difference, we could set last_pre to be the smallest among the remaining, so that sn - last_pre is large. But we need it >= d, and d is the last diff of the prefix. If we make d small, it's easy. But we also need the prefix differences to be non-decreasing. So we can aim to construct the prefix such that its last diff is as small as possible? Actually we want to ensure that there exists a number last_pre from the remaining set such that sn - last_pre >= d. Since we have control over the order, we can try to end with a value that makes that step big enough. The biggest possible step from sn to any remaining is sn - min(remaining) (which might be s2). That could be large, possibly larger than any d we might produce. But we also need to ensure that the step from last_pre to sn is >= d. Since sn is maximum, sn - last_pre is at least something. If we end with the smallest remaining (s2), then sn - s2 could be quite large, likely >= d. But is it always? d might be large if our prefix ends with a large diff. However, we have control: we can design the prefix to have a moderate final diff.
Maybe a simpler construction: After sorting, we can simply output: s_{⌊n/2⌋}, s_{⌊n/2⌋-1}, ..., s_1, s_{⌊n/2⌋+1}, s_{⌊n/2⌋+2}, ..., s_n. That is, start from median, then go down to min, then go up to max. Let's test on example: sorted: -2,4,5,5,6,8. median index? For n=6, floor(n/2)=3, s3=5. Then sequence: s3=5, s2=4, s1=-2, s4=5, s5=6, s6=8 => 5,4,-2,5,6,8. Differences: |5-4|=1, |4-(-2)|=6, |(-2)-5|=7, |5-6|=1, |6-8|=2. That's not non-decreasing (1,6,7,1,2). So no.
What about: s_{⌈n/2⌉}, s_{⌈n/2⌉+1}, s_{⌈n/2⌉-1}, s_{⌈n/2⌉+2}, s_{⌈n/2⌉-2}, ...? Possibly.
Another known pattern: For array a, after sorting, the sequence: a[1], a[3], a[5], ..., a[6]? Not.
Let's search memory: There is a Codeforces problem "A. Sorting Parts" maybe not. The problem ID might be 1506C? Actually I recall a problem "C. Number of Pairs" no. Maybe it's from Round #1630 (Div. 2) problem C? Let me recall: "C. Differential Sorting" maybe? Not exactly.
Wait, I think I've seen a problem: "C. Increase Subarray Sums" no.
Maybe it's "B. Dubious Cyrpto"? No.
I could try to derive from scratch.
Given numbers on line. We want a path with increasing step sizes. Consider starting from some point, then moving to the farthest point in one direction? But step sizes must increase, so the first step is smallest, last step largest. So we can think of the path as starting at some point, then each next step goes to a point that is farther from the current than the previous step from its predecessor. This is like "increasing walk". If we have all points, we can maybe start at a point near the center, then step to a nearby point (small step), then step to a point further away (larger step), and so on, eventually reaching extremes.
Alternatively, think about constructing the sequence in order of increasing step size: we need a sequence of n points p1, p2, ..., pn such that distances d_i = |p_{i+1} - p_i| are non-decreasing. This is similar to constructing a "sorted differences" sequence from the given multiset. Maybe we can first decide the set of differences d_i (which are n-1 numbers) that we want to realize. But we don't have control; the differences are determined by the chosen order.
Observation: The condition is symmetric: if we reverse the sequence, we get the same condition (since the sequence of differences reversed is also non-decreasing? Actually if original d1 <= d2 <= ... <= d_{n-1}, then reversed order gives d_{n-1} >= d_{n-2} >= ... >= d1, which is non-increasing, not same. So reversal doesn't preserve condition unless we also reverse the order of differences? So it's not symmetric.
We can also consider that if we negate all numbers (multiply by -1), the condition remains same because absolute differences unchanged. So we can w.l.o.g. assume sorted.
Maybe there is a known simple solution: sort the array, then output: first the smallest, then the largest, then the second smallest, then the second largest, ... but we saw that gives first diff large. However, if we reverse that order? i.e., start with largest, then smallest, then second largest, then second smallest, ...? Let's test: [1,5,10,11] sorted: 1,5,10,11. Sequence: 11,1,10,5. diffs: 10,9,5 => 10 <= 9 false. Not good.
What about: start with a middle element, then go to an extreme, then to the other middle, then to the other extreme? Example [1,5,10,11] middle maybe 5 or 10. Try 5,11,1,10: diffs:6,10,9 -> 6<=10 true, 10<=9 false. 5,11,10,1: diffs:6,1,9 -> fails. 10,11,5,1: diffs:1,6,4 fails. 10,5,11,1: 5,6,10? Actually |10-5|=5, |5-11|=6, |11-1|=10 -> 5<=6<=10 works! Let's check: 10,5,11,1 yields differences: 5,6,10 which is non-decreasing. So that works! Sequence: 10,5,11,1. Input numbers: 1,5,10,11. So that's a valid rearrangement. Let's see pattern: start with second largest? 10 is second largest, then 5 (second smallest?), then 11 (largest), then 1 (smallest). That's like: pick second largest, then second smallest, then largest, then smallest. For n=4, that seems to work in this case. Check earlier example [1,2,4,8]: second largest is 4, second smallest is 2, largest 8, smallest 1: sequence 4,2,8,1 -> diffs:2,6,7 -> 2<=6<=7 works! Indeed 4,2,8,1 is valid. And [1,3,4,9]: second largest 4, second smallest 3, largest 9, smallest 1: 4,3,9,1 diffs:1,6,8 -> works. [1,5,10,11] we saw works. So for n=4, a general pattern: sorted s1<=s2<=s3<=s4. Then order: s3, s2, s4, s1 yields differences: s3-s2 (since s3>=s2), s4-s2? Wait compute: |s3 - s2| = s3 - s2, |s2 - s4| = s4 - s2 (since s4 >= s2), |s4 - s1| = s4 - s1. We need to check ordering: s3 - s2 <= s4 - s2? Since s3 <= s4, yes s3 - s2 <= s4 - s2. Next, s4 - s2 <= s4 - s1? Since s1 <= s2, s4 - s2 >= s4 - s1? Actually s4 - s2 <= s4 - s1? Wait: s4 - s2 versus s4 - s1: Because s2 >= s1, so subtracting larger gives smaller: s4 - s2 <= s4 - s1. Actually if s2 > s1, then s4 - s2 < s4 - s1. But we need s4 - s2 <= s4 - s1. That's true: s4 - s2 is less than or equal to s4 - s1. However we need the inequality: (second diff) <= (third diff). That is s4 - s2 <= s4 - s1. Yes, since s4 - s2 <= s4 - s1 (because s2 >= s1). So the sequence of diffs is: d1 = s3 - s2, d2 = s4 - s2, d3 = s4 - s1. Since s3 - s2 <= s4 - s2 (as s3 <= s4) and s4 - s2 <= s4 - s1 (as s2 >= s1), it holds. So indeed for any sorted four numbers, the permutation s3, s2, s4, s1 works! (Provided indices: s3 is third smallest, s2 second smallest, s4 largest, s1 smallest). That's a nice pattern.
Check if any case fails due to absolute values: Because we assume s3 >= s2, s4 >= s2, s4 >= s1, all differences are positive and we used actual subtraction without absolute because order ensures positivity? Let's verify: s3 - s2 is non-negative (since s3>=s2). s4 - s2 is non-negative. s4 - s1 is positive. Yes. So works.
Thus for n=4, we have a solution.
Now for n>4, can we extend this idea? Perhaps we can split the array into two halves: lower half L = {s1, s2, ..., s_{k}} and upper half U = {s_{k+1}, ..., s_n} where k = floor(n/2) or something. Then we might interlace them in a specific order to ensure increasing differences.
Let's test n=6. Our earlier example: sorted: -2,4,5,5,6,8. According to the pattern for n=4, we used order: third, second, fourth, first. For n=6, maybe we can generalize: take the middle two? Actually for even n, we could consider: s_{n/2+1}, s_{n/2}, s_n, s_{n-1}, ..., s_1? Let's try to derive.
We need to ensure that differences are non-decreasing. The pattern for n=4 can be seen as: pick an element from the upper half (but not the maximum), then an element from the lower half (but not the minimum), then the maximum, then the minimum. That yields three differences: (upper_mid - lower_mid), (max - lower_mid), (max - min). Those are increasing because upper_mid - lower_mid <= max - lower_mid <= max - min. Indeed.
For more elements, we might chain similar steps: after the minimum, we could then incorporate other numbers? But note the sequence ends with the minimum, and we have max-min as last diff. But we still have other numbers to place before that. In the n=4 case, we placed only four numbers. For n=6, we need to place six. Could we do something like: arrange the middle numbers in a way that yields increasing differences, and then finish with the pattern for the last four? Or perhaps we can arrange as: start with some numbers from the middle, then go down to lower half, then up to upper half, etc., culminating with max and min.
Let's examine the example solution: 5,5,4,6,8,-2. This corresponds to sorted: s1=-2, s2=4, s3=5, s4=5, s5=6, s6=8. Their sequence: s4=5, s3=5, s2=4, s5=6, s6=8, s1=-2. That's like: take the two middle 5's (s3 and s4), then the next lower s2=4, then next higher s5=6, then max s6=8, then min s1=-2. Differences: |5-5|=0, |5-4|=1, |4-6|=2, |6-8|=2, |8-(-2)|=10. So it's non-decreasing.
So pattern for n=6 appears: start from the two middle elements (if n even, the two central ones) but in descending order? Actually they used s4 then s3 (the higher middle then lower middle). Then they went to s2 (next lower), then s5 (next higher), then s6 (max), then s1 (min). So the order is: central elements from upper to lower, then moving outward alternately: after covering the central region, you go to the next lower element (s2), then next higher (s5), then max, then min. But note they did not use s3 after s4? They used both s4 and s3. So effectively they took the sorted array and produced the order: s_{⌈n/2⌉+1? Let's index from 1. n=6, median positions: 3 and 4 (0-index? Actually 1-index). They used s4 (higher median), s3 (lower median), then s2, then s5, then s6, then s1. So it's like: start from the higher median, then lower median, then move leftwards to s2, then move rightwards to s5, then s6, then s1. But why s6 before s1? Because after s5, they used s6 (max) and then s1 (min). This yields final huge jump.
Maybe a general construction: sort array. Then create sequence as follows:
- Let L = sorted list.
- Initialize two pointers: left = 1, right = n.
- We will build the sequence from an initial segment that perhaps goes back and forth.
But we need to ensure differences are non-decreasing.
I recall a known solution for this problem (I think it's Codeforces Round #1742, problem D? Actually there is a problem "C. Number Game" no). Let me search memory: I think I've seen an editorial: "Sort the array. Then output a[⌈n/2⌉], a[⌈n/2⌉-1], ..., a[1], a[⌈n/2⌉+1], a[⌈n/2⌉+2], ..., a[n]" but that didn't work for n=6? We tested earlier 5,4,-2,5,6,8? That's from median and then descending left then ascending right? That was 5 (index3), 4(index2), -2(index1), 5(index4), 6(index5), 8(index6). That gave differences 1,6,7,1,2 - not monotonic. So not that.
But what about: a[⌈n/2⌉], a[⌈n/2⌉+1], a[⌈n/2⌉-1], a[⌈n/2⌉+2], a[⌈n/2⌉-2], ...? Let's test with n=6: indices: ceil(6/2)=3? Actually ⌈n/2⌉ = 3. Then sequence: a3=5, a4=5, a2=4, a5=6, a1=-2, a6=8? Wait order: start a3, then a4, then a2, then a5, then a1, then a6. That yields: 5,5,4,6,-2,8. Differences: 0,1,2,8,10? Actually compute: |5-5|=0, |5-4|=1, |4-6|=2, |6-(-2)|=8, |(-2)-8|=10. That's 0,1,2,8,10 which is non-decreasing. That's a valid arrangement! Indeed 5,5,4,6,-2,8 works? Check: 5,5,4,6,-2,8. Differences: 0,1,2,8,10 -> non-decreasing. That is slightly different from the example output (they had 5,5,4,6,8,-2). Both work. So this pattern seems promising. Let's test on n=4 with this pattern: n=4, ceil(n/2)=2 (since 4/2=2, ceil=2). Indices: a2, a3, a1, a4? Actually sequence: start at index2, then index3, then index1, then index4. Sorted: s1,s2,s3,s4. Then order: s2, s3, s1, s4. Compute differences: |s2-s3| = s3-s2 (since s3>=s2), |s3-s1| = s3-s1, |s1-s4| = s4-s1. Need to check: s3-s2 <= s3-s1? Since s2 >= s1, s3-s2 <= s3-s1. And s3-s1 <= s4-s1? Since s3 <= s4, s3-s1 <= s4-s1. So yes, works! So pattern: for even n, start from index n/2? Actually ceil(n/2) gave index 2 for n=4, which is second element. For n=4, that matches s2,s3,s1,s4. And we earlier found s3,s2,s4,s1 also works, but this is a different valid permutation.
For n=5 (odd), let's test. Suppose sorted: s1,s2,s3,s4,s5. ceil(5/2)=3. Sequence: a3, a4, a2, a5, a1? Actually pattern: start at ceil(n/2)=3, then next index 4, then index 2, then index 5, then index 1. That's s3, s4, s2, s5, s1. Differences: d1=|s3-s4| = s4-s3, d2=|s4-s2|: careful: s4 and s2, since s4>=s2, it's s4-s2, d3=|s2-s5| = s5-s2 (if s5>=s2), d4=|s5-s1| = s5-s1. We need d1<=d2<=d3<=d4. Check: d1 = s4-s3. d2 = s4-s2. Since s2 <= s3? Actually sorted: s2 <= s3 <= s4. So s4-s3 <= s4-s2 because s3 >= s2? Wait: s4-s3 vs s4-s2: because s3 >= s2, subtracting larger gives smaller: s4-s3 <= s4-s2. So d1 <= d2 holds. Next d2 = s4-s2, d3 = s5-s2. Since s5 >= s4, s5-s2 >= s4-s2? Actually if s5 >= s4, then s5-s2 >= s4-s2, so d2 <= d3 holds. Next d3 = s5-s2, d4 = s5-s1. Since s1 <= s2, s5-s2 <= s5-s1 (because subtracting larger gives smaller). So d3 <= d4 holds. So it works for odd n as well. Great!
Thus, the pattern: sort the array. Then create a permutation as follows:
Let m = ceil(n/2). Then output:
b1 = a[m] (1-indexed, after sorting)
b2 = a[m+1]
b3 = a[m-1]
b4 = a[m+2]
b5 = a[m-2]
...
alternating: after the first two (starting from m, then m+1), then go left (m-1), then right (m+2), then left (m-2), then right (m+3), ... until we exhaust all indices.
But careful: The pattern we used for n=6 was: indices: 3,4,2,5,1,6? Actually we had: a3, a4, a2, a5, a1, a6? Let's check: For n=6, ceil(6/2)=3. Sequence: start 3, then 4, then 2, then 5, then 1, then 6. That is indeed alternating after the first two: from index 3 (center-left? Actually 3 is the lower median? Since n even, the two medians are indices 3 and 4. So we start with 3, then 4 (the two medians in order: lower then higher? But we started with lower median then higher? Actually a3 is lower median, a4 higher median. In our earlier test we used a3 then a4. But the pattern we just derived from the "start at ceil(n/2)" gave for n=6: ceil(6/2)=3 -> b1 = a3, b2 = a4, b3 = a2, b4 = a5, b5 = a1, b6 = a6. So it's a3,a4,a2,a5,a1,a6. That yields differences: |a3-a4|, |a4-a2|, |a2-a5|, |a5-a1|, |a1-a6|. We need to verify that this always yields non-decreasing differences. Let's prove.
Assume sorted array x1 <= x2 <= ... <= xn.
Define m = ceil(n/2). Then we construct sequence:
b1 = x_m
b2 = x_{m+1} (if m+1 <= n)
b3 = x_{m-1}
b4 = x_{m+2}
b5 = x_{m-2}
b6 = x_{m+3}
...
Continue until we include all indices. For indices less than 1 or greater than n, we stop when all are used.
We need to check the differences are non-decreasing.
Let's denote the sequence of indices after the first two as we alternate left and right. After b1,b2, we have b3 from left side (m-1), b4 from right (m+2), b5 left (m-2), b6 right (m+3), etc.
We need to compute absolute differences. Since the array is sorted, we can compute the differences as positive numbers because later elements are not necessarily in order; we need to ensure that we always subtract smaller from larger appropriately. But because we are mixing indices, we need to check that the absolute value is simply the larger minus smaller if the two numbers are on opposite sides? Let's analyze.
The sequence we produce is: starting from a central region, then moving outward. The values will fluctuate: after b1 = x_m (some value), b2 = x_{m+1} (>= b1). So first difference d1 = x_{m+1} - x_m (non-negative, possibly zero if equal). Then b3 = x_{m-1} which is <= x_m (since m-1 < m). So b3 is less than or equal to b2? Not necessarily: x_{m-1} <= x_m <= x_{m+1}. So b3 <= b1 <= b2. So b2 is larger than b3 typically. So second difference d2 = |b2 - b3| = b2 - b3 (since b2 >= b3). d2 = x_{m+1} - x_{m-1}. Then b4 = x_{m+2} which is >= x_{m+1} (since sorted). So b4 is >= b3? b4 is larger than b2, so definitely > b3. So d3 = |b3 - b4| = x_{m+2} - x_{m-1} (since b4 > b3). Actually b3 = x_{m-1}, b4 = x_{m+2} so difference = x_{m+2} - x_{m-1}. Then b5 = x_{m-2} (<= x_{m-1}), so d4 = |b4 - b5| = x_{m+2} - x_{m-2} (since b4 > b5). Then b6 = x_{m+3}, d5 = x_{m+3} - x_{m-2}, and so on.
General pattern: after the first step, each subsequent step adds one more index outward on the other side. Specifically:
Let’s define two sequences: L indices: m-1, m-2, m-3, ... down to 1; R indices: m+2, m+3, ... up to n. And we have already used m and m+1 as first two. The order after b2 is: L1 (m-1), R1 (m+2), L2 (m-2), R2 (m+3), L3 (m-3), R3 (m+4), ... until one side exhausted, then we append the remaining indices from the other side? But note that our constructed pattern for n=6 gave: after using L1 (2) and R1 (5), we then used L2 (1) and then R2 (6). Actually we stopped after R2 because both sides exhausted. For n=5 (odd), m=3. Then b1=x3, b2=x4, b3=x2, b4=x5, b5=x1. That's L1 (2), R1 (5), then L2 (1). So after using L1 and R1, we had remaining L2, and we placed it. The order was L1, R1, L2. That matches the alternating pattern: after b2, we go to left, then right, then left (since right exhausted? Actually after R1, there is no R2 because n=5, R indices would be m+2=5? That's R1, then next would be m+3=6 which is out of range, so only left remains. So it's natural to just continue with the remaining left indices in order (from larger to smaller? Actually we used L2 = m-2 =1. That is the next left. So yes, we just continue with left side in decreasing index order? Actually we went from L1 (m-1) to L2 (m-2). That is moving further left. So we are taking left indices in descending order (closer to m first then further). Similarly right indices in ascending order (closer to m+1 first then further). And we interlace them: after b2, we take one from left, then one from right, then one from left, then one from right, etc., until one side runs out, then we take all remaining from the other side in order (continuing the outward progression). But note in n=5, after left, right, left, we had no more right; that's fine. In n=6, after left, right, left, right, both sides exhausted. In n=7? Let's test n=7 sorted: x1..x7, m=ceil(7/2)=4. Then b1=x4, b2=x5, b3=x3 (L1), b4=x6 (R1), b5=x2 (L2), b6=x7 (R2), b7=x1 (L3). That would be the pattern: after b2, L1, R1, L2, R2, L3. That uses all. Let's compute differences and verify they are non-decreasing.
We need to confirm the general proof.
Let’s formalize:
Given sorted array a[1..n] (non-decreasing). Let m = ceil(n/2). Define sequence:
b[1] = a[m]
b[2] = a[m+1] (if m+1 exists, which it does because for n odd, m = (n+1)/2, then m+1 <= n? For n=5, m=3, m+1=4 <=5, yes; for n=4, m=2, m+1=3; for n=3, m=2, m+1=3; for n=3, works? We'll check later. For n=3, this pattern gives b1=a2, b2=a3, b3=a1. That's exactly the solution we had for n=3: second, third, first. Let's test n=3 with numbers [1,2,10]: sorted 1,2,10; b1=2,b2=10,b3=1. Differences: |2-10|=8, |10-1|=9 -> 8<=9 works. For [1,10,11]: 1,10,11 sorted; b1=10,b2=11,b3=1 -> diffs 1,10 -> 1<=10 works. For [1,1,2]: 1,1,2; b1=1,b2=1,b3=2? Actually sorted: a1=1,a2=1,a3=2,m=2 -> b1=a2=1,b2=a3=2,b3=a1=1 -> diffs: |1-2|=1,|2-1|=1 -> 1<=1 works. So n=3 works.
Now for n=2? Not required since n>=3.
So pattern seems to hold for all n>=3.
Now we need to prove that the sequence of absolute differences is non-decreasing.
We'll compute differences in terms of sorted values.
Let’s denote indices used after b2:
Let L_k = m - k, for k = 1,2,..., m-1 (until 1)
Let R_k = m+1 + k, for k = 1,2,..., n - (m+1) (i.e., until n)
Our sequence is:
b1 = a[m]
b2 = a[m+1]
Then for t = 1,2,... until all indices are used:
We add b_{2t+1} = a[L_t] (if L_t >= 1)
We add b_{2t+2} = a[R_t] (if R_t <= n)
If one side exhausts earlier, we continue with the remaining indices from the other side in order of increasing t (i.e., further outward). But note: In the case where we run out of left indices first, the next right index would be placed, but there might be only right indices left; we would add them sequentially as b_{...} = a[R_t] for t increasing. However, our earlier construction for n=5: after b2, we added left (L1), then right (R1), then left (L2). That's because left still had L2; after that, no more left or right? Actually after L2, we have used all indices (since left indices: L1=2, L2=1; right: R1=5). So it's consistent with alternating until one side finishes, then we continue with the remaining from the other side. But note the order after the alternating stops: In n=5, after alternating left, right, left, we have no more. For n=7, alternating left, right, left, right, left (since left has 3,2,1; right has 6,7). That's left,right,left,right,left. So we alternate until all used, and the final element is from left (since left may have one more). In general, if number of elements on left (m-1) and right (n - (m+1)) differ, the longer side will have extra at the end. The interleaving pattern we described (after b2, we take left, then right, then left, then right, ...) will naturally produce a sequence that ends with the side that has more indices, and we take them in order outward.
But is the order exactly that? Let's define:
Let left_indices = [m-1, m-2, ..., 1] (descending)
Let right_indices = [m+2, m+3, ..., n] (ascending)
We start with b1 = a[m], b2 = a[m+1].
Then we interleave: take first left, then first right, then second left, then second right, ... until one list runs out, then append the rest of the other list in order.
This matches the pattern we used.
Now compute differences:
d1 = |b1 - b2| = a[m+1] - a[m] (since a[m+1] >= a[m])
Now consider b2 and b3, where b3 = a[m-1] (first left). Since a[m-1] <= a[m] <= a[m+1], we have b2 >= b3, so d2 = b2 - b3 = a[m+1] - a[m-1].
b3 and b4: b4 = a[m+2] (first right). We have b4 >= a[m+2] >= a[m+1] >= b3? Actually b3 = a[m-1] <= a[m] <= a[m+1] <= a[m+2], so b4 > b3, thus d3 = b4 - b3 = a[m+2] - a[m-1].
b4 and b5: b5 = a[m-2] (second left). We have b5 <= a[m-1] <= a[m+2]? Actually a[m-2] <= a[m-1] <= a[m] <= ... <= a[m+2]. So b4 >= b5? Since a[m+2] >= a[m-2], yes b4 >= b5. So d4 = b4 - b5 = a[m+2] - a[m-2].
b5 and b6: b6 = a[m+3] (second right). Then d5 = a[m+3] - a[m-2].
And so on.
In general, for the alternating steps, when we have just placed a left element (say a[L] where L = m - k) and then the next is a right element (a[R] where R = m+1 + k), the difference is a[R] - a[L]. Then after that right, the next left (if exists) is a[L'] where L' = m - (k+1) (further left), and the difference is a[R] - a[L'].
So the differences follow a pattern:
After b2, the differences are:
d2 = a[m+1] - a[m-1] (between b2 (a[m+1]) and b3 (a[m-1]))
d3 = a[m+2] - a[m-1] (between b3 (a[m-1]) and b4 (a[m+2]))
d4 = a[m+2] - a[m-2] (between b4 (a[m+2]) and b5 (a[m-2]))
d5 = a[m+3] - a[m-2] (between b5 (a[m-2]) and b6 (a[m+3]))
d6 = a[m+3] - a[m-3] (if continue)
...
Generalizing:
For k >= 1, we have two differences associated with each "pair" of left index L_k = m - k and right index R_k = m+1 + k:
- Difference between right element from previous step? Actually let's define step index.
Alternatively, we can see that the differences are of the form:
d_{2k} (for k>=1) corresponds to difference between a[m+1 + (k-1)]? Let's systematically index.
Better: Let’s write the sequence explicitly:
Index: 1: A0 = a[m]
2: B0 = a[m+1]
For i = 1 to min(L_count, R_count) maybe:
2i+1: L_i = a[m - i]
2i+2: R_i = a[m+1 + i] (if i <= R_count)
But careful: when i runs, we might not have R_i if right side exhausted earlier.
But we can think of the differences as:
d1 = B0 - A0 = a[m+1] - a[m].
For i >= 1, we have:
If i <= L_count (i.e., m - i >= 1):
b_{2i+1} = a[m - i] (call L_i)
The preceding element is either b_{2i} if we placed a right element before, or if not, but let's see the order:
Case when both sides have at least i elements: Then the sequence up to i is:
... after B0, we have L_1, R_1, L_2, R_2, ..., L_i, (maybe R_i if we have it).
So for each i, we have differences:
-
Between b_{2i} (which is R_{i-1} for i>=2) and b_{2i+1} (L_i): that's d_{2i} = |R_{i-1} - L_i| = a[m+1+(i-1)] - a[m-i] = a[m+i] - a[m-i]. Wait check: R_{i-1} = a[m+1+(i-1)] = a[m+i]. L_i = a[m-i]. So d_{2i} = a[m+i] - a[m-i] (for i>=1, but careful: for i=1, b_{2}=B0 = a[m+1], b_{3}=L_1 = a[m-1], so d_2 = a[m+1] - a[m-1] which matches formula with i=1: a[m+1] - a[m-1] (since m+i = m+1, m-i = m-1). So yes d_{2} = a[m+1] - a[m-1].
-
Between b_{2i+1} (L_i) and b_{2i+2} (R_i) if exists: d_{2i+1} = |R_i - L_i| = a[m+1+i] - a[m-i] = a[m+i+1] - a[m-i] (for i>=1). For i=1, d_3 = a[m+2] - a[m-1].
Now, we also have the final steps when one side runs out. Suppose left side has more elements than right side. After we have used all right indices up to some i = R_count, then we continue with remaining left indices (L_{R_count+1}, L_{R_count+2}, ...). In that case, after the last right element (R_{R_count}), we have a left element L_{R_count+1}, then next left L_{R_count+2}, etc. The differences then become:
- Between the last right R_{R_count} and the next left L_{R_count+1}: d = a[m+1+R_count] - a[m-(R_count+1)]? Actually R_{R_count} = a[m+1+R_count]; L_{R_count+1} = a[m-(R_count+1)]. So that's d = a[m+1+R_count] - a[m-(R_count+1)]. Then between L_{R_count+1} and L_{R_count+2} (if exists): d = |a[m-(R_count+1)] - a[m-(R_count+2)]| = a[m-(R_count+1)] - a[m-(R_count+2)] (since decreasing). That difference might be smaller, which could break non-decreasing property. So we need to check that this does not happen, i.e., that the pattern of interleaving ensures that the sequence ends before such a left-left adjacency occurs? But wait, in our construction for n=5, after using R1 (a5), we used L2 (a1). That's a step from R1 to L2. Then there is no further element because we are done. So we didn't have two lefts in a row. For n=7, after R2 (a7) and then L3 (a1), that's the final step. So we never have two consecutive left elements because after the final left, we stop. In the case where left side has more than right side, after we exhaust right side, we might have multiple left elements remaining? Let's examine: left count = m-1, right count = n - (m+1). For n=7: m=4, left count =3, right count = 7-5=2. So left has one more than right. Our interleaving order: after b2, we go L1, R1, L2, R2, L3. That's exactly: after using R2 (second right), we have L3 as the next (and final). So we have a sequence: ... R2, L3. No two lefts in a row. So the pattern ensures that we alternate until we run out of the side with fewer elements, then we put all remaining elements from the larger side, but note that the larger side will be taken in order, which might produce consecutive elements from the same side. However, because the larger side will have exactly one more element than the smaller side? Let's check counts.
Left count = m-1.
Right count = n - (m+1) = n - m - 1.
The difference between these counts can be more than 1? Let's compute m = ceil(n/2). For n even: n=2k, then m = k, left count = k-1, right count = 2k - k -1 = k-1. So equal. For n odd: n=2k+1, then m = k+1, left count = k, right count = (2k+1) - (k+1) -1 = 2k+1 - k -2 = k-1. So left count = k, right count = k-1. So left is exactly one more than right. So the counts differ by at most 1. Indeed, because m = ceil(n/2) splits the array such that the left part (indices < m) has size m-1, the right part (indices > m+1) has size n - (m+1). Since we also have indices m and m+1 (the two middle elements for even, and for odd we have m and m+1 where m+1 exists? For odd n, m = (n+1)/2, then m+1 = (n+3)/2, which is > median+1? Let's compute: n=5, m=3, left count=2, right count = 5-4=1. So left is one more. For n=3, m=2, left count=1, right count=3-3=0, left one more. For n=1? not needed. So indeed, the difference is at most 1, and left side has either equal (even n) or one extra (odd n). So after alternating, we will have exactly: start with a[m], a[m+1]; then for i=1 to min(left, right) we add left_i then right_i; and if left > right, we add one more left at the end. That final addition will be from left side (further left) and will be placed after the last right (or after the previous left if right exhausted earlier). So we never have two lefts in a row because left only has at most one extra beyond the alternating pairs, and that extra is appended at the end, so it's preceded by a right (if right existed) or possibly by a left if right count is zero? But if right count is zero (n=3?), then after b2 we would have only left_i? Let's check n=3: m=2, left count=1, right count=0. According to pattern: b1=a2, b2=a3, then we would add left_i? The alternating would try to add left then right, but right doesn't exist, so after b2, we add remaining left (a1) as b3. So sequence: a2,a3,a1. That's preceded by a3 (right? Actually a3 is considered part of the initial two, not a right from the alternating list. But b2 = a3 is not a "right" from the right list; it's a special starting right. Then we add left (a1). So the adjacency is between a3 (which is larger) and a1 (smaller). That's a large difference. No two lefts in a row.
What about n=2? Not needed.
Thus, in all cases, the sequence never has two consecutive elements both from the left side (both indices less than m) or both from the right side (both indices greater than m+1)? Actually could we have two rights in a row? If right count > left count, but we computed right count is never greater than left count because m = ceil(n/2) ensures left count >= right count. Check: For even n, left count = right count. For odd n, left count = right count + 1. So right count <= left count. In alternating, we start with left then right, so we always use a left before a right. If right count were less than left, we finish with a left after the last right, so no two rights. If counts equal, we finish after a right? Let's see even n: left count = right count. Pattern: b1=m, b2=m+1, then L1, R1, L2, R2, ..., L_{k}, R_{k} where k = left count = right count. So the last element is R_k (a right). So the sequence ends with a right, but preceding element is L_k (a left). So no two rights consecutive. Good.
Therefore, the only possible consecutive pairs are of types:
- between a[m] and a[m+1] (first diff)
- between a[m+1] and a[m-1] (second diff)
- between a[m-1] and a[m+2] (third diff)
- between a[m+2] and a[m-2] (fourth diff)
- and so on, alternating left-right, with the final maybe left after a right if left extra.
- Or in case right count zero (n=3), final left after a[m+1] (which is a right index? Actually a[m+1] is considered a right element relative to median, but it's an initial element. But it's fine.
Now we need to verify that the sequence of differences is non-decreasing.
Let's compute differences in the general case.
Case 1: n even. Then m = n/2? Actually ceil(n/2) for even n = n/2. For n=6, m=3; for n=4, m=2. So left count = m-1 = n/2 -1, right count = n - m -1 = n - n/2 -1 = n/2 -1. So both equal, say k = n/2 -1.
Indices:
b1 = a[m]
b2 = a[m+1]
For i = 1..k:
b_{2i+1} = a[m - i]
b_{2i+2} = a[m+1 + i]
So total length = 2 + 2k = 2 + 2*(n/2 -1) = 2 + n -2 = n. Good.
Differences:
d1 = a[m+1] - a[m]
For i = 1..k:
d_{2i} = |b_{2i} - b_{2i+1}| = a[m+1 + (i-1)]? Wait careful: b_{2i} is either a[m+1 + (i-1)]? Let's index:
- For i=1: b2 = a[m+1] (which is b_{2*1}), b3 = a[m-1]. So d2 = a[m+1] - a[m-1].
- For i=2: b4 = a[m+2] (since b_{2*2} = b4 = a[m+2]), b5 = a[m-2]. So d4 = a[m+2] - a[m-2].
- In general, for i from 1 to k: b_{2i} = a[m+ i]? Check: when i=1, b2 = a[m+1]; i=2, b4 = a[m+2]; i=3, b6 = a[m+3]; So indeed b_{2i} = a[m + i] for i>=1? Let's verify: For i=1, a[m+1] -> m+i = m+1, yes; i=2: a[m+2] -> m+2, yes. So b_{2i} = a[m + i] (where i from 1 to k+? Actually when i = k, m + k = m + (n/2 -1) = n/2 + (n/2 -1) = n-1? Let's compute n=6, m=3, k=2. i=2: b4 = a[3+2]=a[5]=6, which is correct (a5). Also b_{2k+2}? Wait last index is b_{2k+2} = b_{2k+2} = b_{2(k+1)}? Actually after the final, b_{2k+2} = a[m+ (k+1)]? Let's see: For k=2, we have b1, b2, b3, b4, b5, b6. b2 = a[m+1] = a4? Actually careful: For n=6, a indexing: 1..6. m=3. a[m+1] = a4 = 5? Wait sorted: [-2,4,5,5,6,8] index: 1:-2,2:4,3:5,4:5,5:6,6:8. So m=3, a[m]=5, a[m+1]=a4=5. So b2 = a4 = 5. That's a[m+1] indeed. But according to b_{2i} = a[m+i] for i=1 gives a[3+1]=a4=5, ok. For i=2, b4 = a[3+2]=a5=6, which is b4. So that matches. For i=3? There is no i=3 because k=2, so b6 is not b_{2i} but b_{2k+2}? Actually b6 is the last element, which is b_{2k+2}? Since total n = 2+2k, then indices: 1,2,3,...,2+2k. So the last index is 2k+2. But our pattern lists b_{2i+2} for i from 1..k gives b4, b6,...? Wait we have b_{2i+2} for i=1 => b4, i=2 => b6. So indeed b_{2i+2} = a[m+1 + i]? Let's re-derive:
Our construction: b1 = a[m]; b2 = a[m+1]; then for j=1 to k:
b_{2j+1} = a[m - j]
b_{2j+2} = a[m+1 + j] (since m+1 + j)
So for j=1: b3 = a[m-1], b4 = a[m+2]? Wait m+1 + 1 = m+2, but earlier we had b4 = a[m+2]. Yes that matches. For j=2: b5 = a[m-2], b6 = a[m+3]. So b_{2j+2} = a[m+1 + j] = a[m + j + 1]. So b_{2j} for j>=2? Actually b2 is a[m+1] which is a[m+1+0] = a[m+1]; that can be thought as j=0? But we can handle separately.
Thus, differences:
d1 = a[m+1] - a[m]
For each j from 1 to k:
d_{2j} = |b_{2j} - b_{2j+1}|. Now b_{2j} is either a[m+1] when j=1? Actually for j=1, b_{2j}=b2? That's a[m+1]. For j=2, b_{2j}=b4 which is a[m+2]. So in general, for j>=1, b_{2j} = a[m+1 + (j-1)]? Let's find a unified formula.
Better to treat two sequences of differences:
After b2, we have:
- d2 = |b2 - b3| = a[m+1] - a[m-1] (since b2 = a[m+1], b3 = a[m-1])
- d3 = |b3 - b4| = a[m+2] - a[m-1] (since b4 = a[m+2])
- d4 = |b4 - b5| = a[m+2] - a[m-2] (b5 = a[m-2])
- d5 = |b5 - b6| = a[m+3] - a[m-2] (b6 = a[m+3])
- d6 = |b6 - b7| = a[m+3] - a[m-3] (if exists)
- ...
So we see pairs: d2,d3 involve same left index m-1; d4,d5 involve left m-2; etc. In general, for each k >=1, we have two differences: one between a right element (a[m + k]?) and a left element (a[m - k])? Let's define:
For k from 1 to L (where L = left count), we have:
- A difference that involves right element a[m + k] and left element a[m - (k-1)]? Hmm.
Let's index by the step number t from 2 to n.
But to prove monotonicity, we can show that the differences are non-decreasing by showing each consecutive pair of differences satisfies d_i <= d_{i+1}.
We can attempt to prove by comparing expressions:
We have (presuming n even for simplicity, but odd similar):
d1 = a[m+1] - a[m].
d2 = a[m+1] - a[m-1].
Since a[m] >= a[m-1], we have a[m+1] - a[m] <= a[m+1] - a[m-1] (because subtracting a smaller number yields larger difference). Actually careful: a[m+1] - a[m] <= a[m+1] - a[m-1] because a[m] >= a[m-1] implies -a[m] <= -a[m-1], so a[m+1]-a[m] <= a[m+1]-a[m-1]. So d1 <= d2.
Next, d2 = a[m+1] - a[m-1] and d3 = a[m+2] - a[m-1]. Since a[m+2] >= a[m+1], we have a[m+1] - a[m-1] <= a[m+2] - a[m-1]. So d2 <= d3.
Next, d3 = a[m+2] - a[m-1] and d4 = a[m+2] - a[m-2]. Since a[m-1] >= a[m-2], subtracting larger gives smaller: a[m+2] - a[m-1] <= a[m+2] - a[m-2] (because -a[m-1] <= -a[m-2]? Wait: if a[m-1] >= a[m-2], then a[m+2] - a[m-1] <= a[m+2] - a[m-2] because subtracting a larger number yields a smaller result? Actually let's check numeric: suppose a[m-2]=10, a[m-1]=12, a[m+2]=20. Then d3=20-12=8, d4=20-10=10. So indeed 8 <= 10. So inequality holds because a[m-1] >= a[m-2] implies a[m+2] - a[m-1] <= a[m+2] - a[m-2]. So d3 <= d4.
Next, d4 = a[m+2] - a[m-2] and d5 = a[m+3] - a[m-2]. Since a[m+3] >= a[m+2], we have d4 <= d5.
And so on. So each adjacent pair of differences follows either from increasing the right index (which increases the difference) or decreasing the left index (which also increases the difference). The pattern of differences alternates between these two types: one where left index is same and right index increases, and one where right index is same and left index decreases (i.e., becomes smaller). Both operations produce a larger or equal difference.
Thus, as long as the sequence of differences is exactly as described (alternating these two types), we get monotonic non-decreasing.
Now we must also consider the transition from the last such pair to the final step if there is an extra left at the end (odd n case). In odd n, after the alternating, we have an extra left element after the last right. Let's check with n=5 (m=3). Differences we computed:
d1 = a[4] - a[3] (a4 - a3)
d2 = a[4] - a[2] (a4 - a2)
d3 = a[5] - a[2] (a5 - a2) (since b3=a2? Actually careful: for n=5, sorted a1..a5, m=3. Sequence: b1=a3, b2=a4, b3=a2, b4=a5, b5=a1. Differences: d1 = a4-a3, d2 = |a4-a2| = a4-a2, d3 = |a2-a5| = a5-a2, d4 = |a5-a1| = a5-a1. We need to check d3 <= d4? d3 = a5-a2, d4 = a5-a1. Since a2 >= a1, a5-a2 <= a5-a1, so d3 <= d4. Also d2 <= d3? d2 = a4-a2, d3 = a5-a2. Since a5 >= a4, a4-a2 <= a5-a2, so d2 <= d3. And we already have d1 <= d2 as before. So monotonic holds.
Now, what about the transition from the last alternating step to the extra left? In odd n, after the last right (b_{2k+2}? Actually let's set k = right count = (n - (m+1)) = (n - m -1). For odd n, left count = k+1. The alternating goes: after b2, we do for i=1..k: L_i, R_i. Then we have one more left: L_{k+1}. So the differences are:
- After the last right R_k and the extra left L_{k+1}: d = |R_k - L_{k+1}| = a[m+1 + k] - a[m - (k+1)].
- The previous difference (the one before that) would be either between L_k and R_k (if we had L_k then R_k) or between R_{k-1} and L_k? Actually we need to map indices.
Let's do generic for odd n: n=2k+1. Then m = k+1. left count = k, right count = k-1? Wait earlier for odd: n=2k+1, m = k+1, left count = m-1 = k, right count = n - (m+1) = 2k+1 - (k+2) = k-1. So left count = k, right count = k-1. That's different from my earlier count for n=5: n=5 => k=2, left=2, right=1. Yes matches. So alternating: after b1=m, b2=m+1, we have for i=1..right count (i=1 to k-1): b_{2i+1}=a[m-i], b_{2i+2}=a[m+1+i]. Then we have remaining left indices: after that, we have left indices from i = right_count+1 to left_count: i = k (since left count = k). So we add b_{2right_count+3} = a[m - (right_count+1)], then possibly further left? But left count - right_count = 1, so only one extra left. So sequence length = 2 + 2right_count + 1 = 2 + 2(k-1) + 1 = 2k+1 = n. So final element is a[m - (right_count+1)] = a[m - k] = a[(k+1)-k] = a[1]. So last element is a1.
Now differences: Let's denote r = right_count = k-1. Then we have:
d1 = a[m+1] - a[m]
For i=1 to r:
d_{2i} = a[m+1+(i-1)]? Actually we should compute carefully.
Better to compute differences directly using the alternating pattern and then check the last step.
We can rely on the observation that the differences are of the form:
- d_{odd indices after maybe? Actually the monotonic property we observed seems to hold for the described construction in all cases because the process of either increasing the right index or decreasing the left index continues throughout.
Let's try to prove generally.
Define two sequences: for t from 0 onward (t representing "layer"):
Let left_idx(t) = m - t, right_idx(t) = m+1 + t.
We start with t=0: we have elements a[m] and a[m+1].
For t=1, we introduce a[left_idx(1)] = a[m-1], then a[right_idx(1)] = a[m+2] (if exists). For t=2, a[m-2], a[m+3], etc.
Now, the differences are:
Between a[m+1] (right_idx(0)? Actually a[m+1] is right_idx(0)? Since right_idx(0) = m+1) and a[m-1] (left_idx(1)): d = a[m+1] - a[m-1] = right_idx(0) - left_idx(1).
Between a[m-1] and a[m+2]: d = a[m+2] - a[m-1] = right_idx(1) - left_idx(1).
Between a[m+2] and a[m-2]: d = a[m+2] - a[m-2] = right_idx(1) - left_idx(2).
Between a[m-2] and a[m+3]: d = a[m+3] - a[m-2] = right_idx(2) - left_idx(2).
And so on.
In general, after we have introduced left_idx(t) and right_idx(t), the differences are of two types:
Type A: between right_idx(t-1) and left_idx(t): d = right_idx(t-1) - left_idx(t). (for t>=1)
Type B: between left_idx(t) and right_idx(t): d = right_idx(t) - left_idx(t). (if right_idx(t) exists)
And when we run out of right_idx(t) (i.e., t > right_count), we may have only Type A for final t (which is left_idx(t) and then no following right). But also after the last right, we may have a Type A to the final left (which is left_idx(t) for t = left_count). Actually if right_count = r, then for t = 1..r, we have both Type A and Type B differences. For t = r+1 (if left_count > r), we have Type A difference between right_idx(r) (last right) and left_idx(r+1). That's the final difference before the end? Actually after that, there is no further element, so that Type A is the last difference. So we have the following sequence of differences:
d1 = right_idx(0) - left_idx(0) ? Actually left_idx(0) = m, right_idx(0)=m+1, so d1 = right_idx(0) - left_idx(0) = a[m+1]-a[m].
Then for t=1 to r:
d_{2t} = right_idx(t-1) - left_idx(t) (Type A)
d_{2t+1} = right_idx(t) - left_idx(t) (Type B)
(For t=1, d2 = right_idx(0)-left_idx(1), d3 = right_idx(1)-left_idx(1). For t=2, d4 = right_idx(1)-left_idx(2), d5 = right_idx(2)-left_idx(2), etc.)
After that, if left_count > r (i.e., odd n case), then we have one more difference: d_{2r+2} = right_idx(r) - left_idx(r+1) (Type A for t=r+1). This is the last difference.
If left_count == r (even n case), then there is no extra left, and the last difference is Type B for t=r: d_{2r+1} = right_idx(r) - left_idx(r). But note the total number of differences is n-1. In even n, n = 2r+2? Let's verify: For even n, n=2k, m=k, left_count = k-1, right_count = k-1 => r = k-1. Then total differences = n-1 = 2k-1. Our formula: d1 + for t=1..r: 2 differences each => 1 + 2r = 1+2(k-1)=2k-1. That matches, and the last difference is Type B for t=r (since left_count = r). In odd n, n=2k+1, m=k+1, left_count = k, right_count = k-1 => r = k-1. Total differences = n-1 = 2k. Our formula: d1 + 2r differences = 1+2(k-1)=2k-1, plus one extra Type A = total 2k. Good.
Now, we need to show that this sequence is non-decreasing.
We have:
d1 = right_idx(0) - left_idx(0) = a[m+1]-a[m].
For t from 1 to r:
We have two consecutive differences: d_{2t} and d_{2t+1}.
We need to show:
- d_{2t-1} <= d_{2t} (transition from previous Type B to current Type A? Actually we need to consider all adjacent pairs.)
Let's list all differences in order:
Index: 1: d1
2: d2 = right_idx(0)-left_idx(1)
3: d3 = right_idx(1)-left_idx(1)
4: d4 = right_idx(1)-left_idx(2)
5: d5 = right_idx(2)-left_idx(2)
6: d6 = right_idx(2)-left_idx(3)
...
General for t>=1:
d_{2t} = right_idx(t-1) - left_idx(t)
d_{2t+1} = right_idx(t) - left_idx(t)
Now, we need to verify monotonicity between each adjacent pair:
-
Between d1 and d2: d1 = right_idx(0)-left_idx(0), d2 = right_idx(0)-left_idx(1). Since left_idx(0) >= left_idx(1) (because left_idx decreases as t increases), we have right_idx(0)-left_idx(0) <= right_idx(0)-left_idx(1). So d1 <= d2.
-
Between d2 and d3: d2 = right_idx(0)-left_idx(1), d3 = right_idx(1)-left_idx(1). Since right_idx(1) >= right_idx(0), we have right_idx(0)-left_idx(1) <= right_idx(1)-left_idx(1). So d2 <= d3.
-
For t>=1, between d_{2t+1} and d_{2t+2} (i.e., d3 and d4, d5 and d6, ...): d_{2t+1} = right_idx(t)-left_idx(t), d_{2t+2} = right_idx(t)-left_idx(t+1). Since left_idx(t) >= left_idx(t+1), we have right_idx(t)-left_idx(t) <= right_idx(t)-left_idx(t+1). So d_{2t+1} <= d_{2t+2}.
-
Between d_{2t} and d_{2t+1} for t>=2? Actually we already covered d2 and d3 (t=1). For t>=2, we need between d_{2t} and d_{2t+1}: d_{2t} = right_idx(t-1)-left_idx(t), d_{2t+1} = right_idx(t)-left_idx(t). Since right_idx(t) >= right_idx(t-1), we have right_idx(t-1)-left_idx(t) <= right_idx(t)-left_idx(t). So d_{2t} <= d_{2t+1}. But note that for t=1, d2 and d3 we already did; this general case covers t>=1 if we define right_idx(t-1) for t=1: right_idx(0) is defined. So it's consistent.
Thus, all adjacent pairs are non-decreasing.
Now, we also have the final extra difference in odd n: after the last Type B? Actually in even n, the sequence ends with d_{2r+1} (which is a Type B). There is no further comparison. In odd n, after the last Type B (which would be d_{2r+1}? Actually for odd n, since we have extra left, the sequence of differences ends with d_{2r+2} = right_idx(r) - left_idx(r+1). We need to compare d_{2r+1} (which is the last Type B) with d_{2r+2} (the extra Type A). But we already have the comparison between d_{2t+1} and d_{2t+2} for t = r? Indeed, if we set t = r, then d_{2r+1} = right_idx(r)-left_idx(r), d_{2r+2} = right_idx(r)-left_idx(r+1). And we argued that d_{2t+1} <= d_{2t+2} because left_idx(r) >= left_idx(r+1). So this holds. So all good.
Thus, the construction always yields a valid rearrangement.
So algorithm:
For each test case:
- Read n and array a.
- Sort a.
- Compute m = ceil(n/2). Since we are using 1-indexed in explanation, in 0-indexed programming we need to adjust. Let's define sorted array s[0..n-1] (0-indexed). Then we need to map indices.
In 0-indexed:
Sorted: s[0] <= s[1] <= ... <= s[n-1].
We want m = ceil(n/2) in 1-indexed. Convert to 0-index: Let mid = (n-1)//2? Actually careful.
1-indexed: m = ceil(n/2). For n=6, m=3 (1-indexed). In 0-indexed, that corresponds to index 2 (since index 0 is first). So mid = m-1 = ceil(n/2)-1.
But we also need the element at m+1 (1-indexed) which is index m (since 1-index to 0-index: idx = value-1). So m (1-indexed) -> idx = m-1; m+1 -> idx = m.
Thus, if we let p = n//2? Let's compute p = n//2. For n even, n=6, p=3. Ceil(n/2) = 3. So p = n//2 = 3. So p (1-indexed) is the first index of the second half? Actually with 0-index, indices: 0,1,2,3,4,5. For n=6, we want m-1 = 2, and m = 3. So the two central elements are indices 2 and 3. p = n//2 = 3, so p-1 = 2, p=3. So we can set left_center = p-1, right_center = p. For n odd, n=5, p = n//2 = 2. Ceil(5/2)=3. So central elements? Sorted indices 0,1,2,3,4. We want m=3 (1-index) -> index 2, and m+1=4 -> index 3. So left_center = 2, right_center = 3. And p = 2? Actually p = n//2 = 2, so p is not directly the center. But p-1=1, p=2 are not the central two. So we need to be careful.
Better: define mid = (n-1)//2? For n=5, (5-1)//2 = 2, which gives index 2 (the median). Then the next index is mid+1 = 3. That matches: index 2 and 3 are the two middle elements? Actually for odd n, the two middle elements are median and the next one. Yes. For n=5, sorted: a0,a1,a2,a3,a4. The median is a2, and the next is a3. So we can set: first = mid, second = mid+1, where mid = (n-1)//2? Let's test: n=5, (5-1)//2=2 -> OK. n=6, (6-1)//2 = 2 (since 5//2=2). That gives mid=2, mid+1=3, which are the two central indices. Good. So define mid = (n-1)//2. Then b0 = s[mid], b1 = s[mid+1]. That's consistent for both even and odd. Indeed, for even n=6, (5)//2=2, correct. For n=4, (3)//2=1, mid=1, mid+1=2 -> indices 1 and 2 are the two middle? Sorted of 4: indices 0,1,2,3. The two middle are 1 and 2, yes.
Thus, we can use mid = (n-1)//2.
Now, we need to generate the rest of the sequence by alternating left and right from there.
We have used indices mid and mid+1.
Let left = mid-1, right = mid+2.
We will alternate: while left >=0 and right < n, we first add s[left] then s[right]; then decrement left, increment right. However, the order is: after b1 (s[mid+1]), we add s[left] (first left), then s[right] (first right), then next left, next right, etc. That matches: b2 = s[mid+1]; b3 = s[left1]; b4 = s[right1]; b5 = s[left2]; b6 = s[right2]; ...
But careful: In our construction, we said after b2 (which is s[mid+1]), we first add a left element (s[mid-1]), then a right element (s[mid+2]), then left, right, etc. So the loop should be:
Initialize result list: [ s[mid], s[mid+1] ].
Set L = mid-1, R = mid+2.
While L >= 0 and R < n:
result.append(s[L])
result.append(s[R])
L -= 1
R += 1
After this loop, one of the sides may still have elements left. Since left count >= right count (as argued), after loop termination, if L >=0 (meaning left side still has elements) then we need to add the remaining left elements in order (from current L down to 0). But careful: In our earlier analysis, after exhausting right, we may have one extra left (for odd n). In the loop, we stop when either L < 0 or R >= n. Since left count >= right count, it's possible that after the loop, L may still be >=0 (right exhausted), and we need to add the remaining left elements. But do we add them in the same order (decreasing index)? Let's see: For n=5, mid=2, initial result: [s2, s3]. L=1, R=4. Loop: L>=0 and R<5? R=4 <5, so enter loop: append s[1] (index1), append s[4] (index4). Then L becomes 0, R becomes 5. Now loop condition: L=0>=0, R=5 not <5, so exit. Now L=0 still >=0, so we need to add remaining left? But we have already used all indices? We have used indices: 2,3,1,4. Left index 0 is remaining. According to our pattern, for n=5, the sequence should be: s2, s3, s1, s4, s0. Wait our current result: [s2, s3, s1, s4]. That's missing s0. So we need to append s[0] at the end. That's consistent: after loop, we have L=0, and we need to add s[L] (and any further left, but L=0 so just one). So we do while L >= 0: result.append(s[L]); L-=1.
What about the case when right count > left count? That never happens as argued. But we should also handle the case when after loop, R < n (i.e., right side still has elements). Could that happen? Only if left count < right count, which does not occur. But to be safe, we can also add remaining right elements if any (though not needed). But according to counts, after loop, either both L<0 and R>=n (even n) or L>=0 and R>=n (odd n). For even n, both sides finish simultaneously? For n=6, mid=2, initial: [s2,s3], L=1,R=4. Loop: L>=0 and R<6 -> true: append s[1], append s[4]; L=0,R=5. Loop again: L>=0 and R<6 -> true: append s[0], append s[5]; L=-1,R=6. Loop ends, L=-1,R=6. No remaining. So even n ends exactly.
For n=4, mid=1, initial [s1,s2], L=0,R=3. Loop: L>=0 and R<4 -> true: append s[0], append s[3]; L=-1,R=4. End. Works.
For n=3, mid=1 (since (3-1)//2=1), initial [s1,s2] (indices 1 and 2). L=0,R=3? R=mid+2=3 which is >= n (3). So loop not entered. Then L=0 >=0, so we append s[0]. Result: [s1,s2,s0] -> indices 1,2,0. That's the sequence we wanted? For n=3 sorted, we want b1 = s[1], b2 = s[2], b3 = s[0]. Yes.
Thus, the algorithm is:
- Sort array.
- Compute mid = (n-1)//2.
- Initialize answer list with [sorted[mid], sorted[mid+1]].
- Set left = mid-1, right = mid+2.
- While left >= 0 and right < n:
answer.append(sorted[left])
answer.append(sorted[right])
left -= 1
right += 1
- After loop, while left >= 0:
answer.append(sorted[left])
left -= 1
- (Optionally, while right < n: but shouldn't happen, but we can include for safety: while right < n: answer.append(sorted[right]); right += 1)
This yields a permutation of length n.
We need to ensure that this works for all n >= 3. Let's test on some random cases mentally.
Test n=3, input [10,1,5] -> sorted [1,5,10], mid=1 -> answer: [5,10,1] diff:5,9 -> 5<=9 good.
Test n=3 all equal: [3,3,3] sorted [3,3,3], answer [3,3,3] diff 0,0 -> good.
Test n=4, input [1,100,50,2] -> sorted [1,2,50,100], mid=1 -> answer: [2,50,1,100]? Let's compute: sorted: [1,2,50,100]; mid=1 => b0=2, b1=50; left=0, right=3; loop: append s[0]=1, append s[3]=100; result: [2,50,1,100]. Differences: |2-50|=48, |50-1|=49, |1-100|=99 -> 48<=49<=99 good.
What about another arrangement: n=4 sorted [1,1,1,2] -> mid=1 => b0=1 (index1), b1=1 (index2), left=0, right=3: loop: append s[0]=1, append s[3]=2 => result [1,1,1,2] differences:0,0,1 -> good.
n=5 sorted [1,2,3,4,5]: mid=2 => b0=3,b1=4; left=1,right=4? Wait mid+2=4? Actually mid+2 = 2+2=4, right=4; left=1. Loop: left>=0 and right<5? right=4 <5 yes, so append s[1]=2, append s[4]=5 => result [3,4,2,5]; left=0,right=5; exit loop; left=0 so append s[0]=1. Final: [3,4,2,5,1]. Differences: |3-4|=1, |4-2|=2, |2-5|=3, |5-1|=4 => 1<=2<=3<=4 works.
n=5 sorted [1,1,2,3,4]: mid=2 => b0=2,b1=3; left=1,right=4? mid+2=4, right=4; left=1 -> loop: append s[1]=1, append s[4]=4 => [2,3,1,4]; left=0,right=5; append s[0]=1 -> [2,3,1,4,1]. Differences: |2-3|=1, |3-1|=2, |1-4|=3, |4-1|=3 -> 1<=2<=3<=3 works.
n=5 sorted [1,2,10,11,12]: mid=2 => b0=10,b1=11; left=1,right=4? mid+2=4 -> s[4]=12; loop: append s[1]=2, append s[4]=12 -> [10,11,2,12]; left=0, append s[0]=1 -> [10,11,2,12,1]. Differences: |10-11|=1, |11-2|=9, |2-12|=10, |12-1|=11 -> 1<=9<=10<=11 good.
n=6 sorted [1,2,10,11,12,100]: mid = (6-1)//2 = 2 (since 5//2=2). b0=s[2]=10, b1=s[3]=11? Wait mid+1 = 3 -> s[3]=11. left=1,right=4. Loop: append s[1]=2, append s[4]=12 -> [10,11,2,12]; left=0,right=5. Loop again: append s[0]=1, append s[5]=100 -> [10,11,2,12,1,100]. Differences: |10-11|=1, |11-2|=9, |2-12|=10, |12-1|=11, |1-100|=99 -> 1<=9<=10<=11<=99 works.
n=6 sorted [1,1,1,1,2,3]: mid=2 => b0=s[2]=1, b1=s[3]=1; left=1,right=4 -> loop: append s[1]=1, append s[4]=2 -> [1,1,1,2]; left=0,right=5 -> loop: append s[0]=1, append s[5]=3 -> [1,1,1,2,1,3]. Differences: 0,1,1,1,2? Let's compute: positions: 1-1=0, 1-1=0? Actually careful: [1,1,1,2,1,3]. Differences: |1-1|=0, |1-1|=0, |1-2|=1, |2-1|=1, |1-3|=2 => sequence 0,0,1,1,2 non-decreasing. Works.
Thus the construction appears robust.
Now, we must ensure that we are not missing any elements. In the loop we use while left>=0 and right<n, we append left then right. After loop, we append remaining left. But what if right side still has elements? As argued, not needed but we can add for safety: while right < n: append sorted[right]; right+=1. This would handle cases where left count < right count (which shouldn't happen but if n small? For n=2? Not needed). But let's be thorough: Since left count = mid (since indices 0..mid-1 count = mid) and right count = n - (mid+2) = n - mid - 2. For n even, n=2k, mid = (2k-1)//2 = k-1 (since (2k-1)//2 = k-1). Then left count = k-1, right count = 2k - (k-1) -2 = k-1. Equal. For n odd, n=2k+1, mid = (2k)//2 = k. Then left count = k, right count = (2k+1) - (k+2) = k-1. So left count = right count + 1. So indeed left count >= right count. In the loop we consume one left and one right each iteration. The loop continues while both sides have elements. Since right count <= left count, the loop will exit when either left runs out (which would require right also run out? Actually if right count < left count, then after right runs out, left still has elements, loop condition fails because right>=n, left may still be >=0. That's correct. If left count == right count, loop will consume all, leaving both sides empty. So after loop, only possible remaining are left elements (if any). So we only need to add remaining left. But to be safe (if implementation off-by-one), we can also add right, but it would be empty.
Thus algorithm is O(n log n) per test case due to sorting. Since total n <= 1e5, sorting total O(N log N) is fine.
Now we need to output the rearranged array for each test case.
Let's also consider if there is any scenario where mid+1 is out of bounds? Since n>=3, mid = (n-1)//2, mid+1 <= n-1? For n=3, mid=1, mid+1=2 valid. For n=4, mid=1, mid+1=2 valid. For n=5, mid=2, mid+1=3 valid. So okay.
Edge case: n=3, after initial, left = mid-1 could be 0, right = mid+2 = 4 which is out of bounds, so loop not executed, then we append left (0). Works.
Now we should confirm that the output matches the sample. Sample 1: n=6, a = [5,-2,4,8,6,5]. Sorted: [-2,4,5,5,6,8]. mid = (6-1)//2 = 2 (0-index). So b0 = s[2]=5, b1=s[3]=5. left=1 -> s[1]=4, right=4 -> s[4]=6: add 4,6 => now list [5,5,4,6]. left becomes 0, right becomes 5. Loop again since left>=0 and right<6: add s[0]=-2, s[5]=8 => [5,5,4,6,-2,8]. That's exactly the sample output? Sample output is "5 5 4 6 8 -2". Our order: 5,5,4,6,-2,8. Slight difference: they have 5 5 4 6 8 -2 (i.e., after 6 they placed 8 then -2). Both are valid. Our construction gave -2 then 8, which yields differences: after 6, -2 diff=8? Actually |6 - (-2)| = 8, then |(-2) - 8| = 10. That's 2,8,10? Wait earlier we computed differences for [5,5,4,6,-2,8]: 0,1,2,8,10 -> 0<=1<=2<=8<=10 works. Theirs: 5,5,4,6,8,-2 differences: 0,1,2,2,10? Actually |6-8|=2, |8-(-2)|=10, so differences: 0,1,2,2,10 -> also non-decreasing (2<=2). Both valid. So our answer is acceptable.
Sample 2: n=4, a = [8,1,4,2]. Sorted: [1,2,4,8]. mid = (4-1)//2=1 -> b0=s[1]=2, b1=s[2]=4. left=0 -> s[0]=1, right=3 -> s[3]=8 => sequence [2,4,1,8]. Differences: |2-4|=2, |4-1|=3, |1-8|=7 -> 2<=3<=7 works. Sample output is "1 2 4 8". That's different but also valid. So our output would be "2 4 1 8", which is fine.
Thus algorithm is correct.
Now we should consider if there is any simpler solution without sorting? Sorting is straightforward.
Complexities: O(n log n) per test case, total O(N log N) where N sum <= 1e5, which is fine.
Now we need to implement in code.
Pseudo:
t = read int
for each test case:
n = read int
a = list of n ints
sort(a)
mid = (n-1)//2
ans = [a[mid], a[mid+1]]
left = mid-1
right = mid+2
while left >= 0 and right < n:
ans.append(a[left])
ans.append(a[right])
left -= 1
right += 1
while left >= 0:
ans.append(a[left])
left -= 1
# optional while right < n: but not needed
print ans separated by space
Double-check for n=3: mid=1, ans = [a[1], a[2]]; left=0, right=3; while condition false; then while left>=0: ans.append(a[0]) -> [a1,a2,a0]; done.
For n=4: mid=1, ans=[a1,a2]; left=0,right=3; while: append a0, append a3; left=-1,right=4; while left false. Output: [a1,a2,a0,a3]. Works.
For n=5: mid=2, ans=[a2,a3]; left=1,right=4; while: append a1, append a4; left=0,right=5; exit loop; while left: append a0; output: [a2,a3,a1,a4,a0].
All good.
Now we should also consider if there is any case where mid+1 index is out of bounds? Since n>=3, mid+1 <= n-1? For n=3, mid=1, mid+1=2 okay. For n=3, mid+2=4 out of bounds but we don't access without check.
Edge: n=3, after initial, left=0, right=4, loop condition ensures we don't access out of bounds.
Now, we might also consider alternative construction that doesn't require sorting? But sorting is fine.
Thus we have a solution.
But wait, the problem statement says "It's always possible to find such rearrangement." So our construction proves it.
Now, confirm that the differences are non-decreasing as proven. The proof is simple.
Implementation details:
-
Use Python for simplicity. Input up to 1e5 total numbers, so reading with sys.stdin.
-
For each test case, sort the list.
-
Construct answer as list.
Potential pitfalls:
-
In Python, if n is large and we use loops, it's O(n) per test case, fine.
-
Ensure we convert to ints correctly.
Testing with some random cases using mental or quick script would confirm.
We should also test a case where all numbers are same: e.g., n=5 all 0. Sorted all 0. mid=2, ans = [0,0]; left=1,right=3: while: append 0,0; left=0,right=4: while: append 0,0; left=-1; output all zeros. Differences all 0, non-decreasing.
Test with negative numbers: works.
Thus solution is ready.
But is there any case where our constructed sequence violates the condition? Let's double-check the step where we append remaining left elements after the loop. In odd n, after loop we have one extra left. That last appended element is s[left] where left is the smallest index. The last difference is between previous element (which was the last right? Actually in the loop, we added a right element as the last element before exit? Let's examine odd n case: For n=5, after loop we had: after first iteration, we appended left (s[1]) and then right (s[4]). At that point, left=0, right=5. Loop condition fails because right>=5. So the last element in the list currently is s[4] (right). Then we go to while left>=0: append s[0]. So the new last element is s[0]. The difference between s[4] and s[0] is computed. In our pattern, that is d_last = right_idx(r) - left_idx(r+1). And we argued that d_{2r+1} (which was right_idx(r)-left_idx(r)) <= d_{2r+2} = right_idx(r)-left_idx(r+1) because left_idx(r) >= left_idx(r+1). But wait, d_{2r+1} is the difference between left_idx(r) and right_idx(r)? Actually earlier we said for odd n, after the loop we have used left and right pairs for t=1..r. The last difference before the extra left is between left_idx(r) and right_idx(r)? Let's see the order: In the loop, we appended left then right. So after processing t from 1 to r, we have appended for each t: left_idx(t) then right_idx(t). So the sequence up to before the extra left is: ... left_idx(r), right_idx(r). So the last difference computed before the extra left is between left_idx(r) and right_idx(r) = d_{2r+1} (if we count correctly). Then we append extra left: left_idx(r+1). So the new difference is between right_idx(r) and left_idx(r+1) = d_{2r+2}. And we have d_{2r+1} <= d_{2r+2} as argued. So it's fine.
Now, what about the case where after loop we have multiple left elements? As argued, left count is at most right count+1, so at most one extra left. So while left>=0 may add multiple if something off? But in our counts, after loop, if left count > right count, the difference is exactly 1. Because left count = right count + 1. After consuming right count pairs, left remaining count = left count - right count = 1. So while left>=0 will run exactly once (since left will be exactly 0 after decrement? Actually after loop, left could be 0 (if left count = right count +1). It will add that one element, then decrement to -1, exit. So no multiple. However, if we had an off-by-one where left count > right count+1? That cannot happen given our definitions. But to be safe, while loop is fine.
Now consider if we mistakenly set mid incorrectly for even n? For n=6, (n-1)//2=2, correct. For n=4, (3)//2=1 correct.
Thus, we can implement.
Now we might want to output the array as space-separated.
Potential issue: The problem says t up to 1e4, total n up to 1e5. Sorting each test case individually is fine.
Now, let's produce the final answer.
But before finalizing, check the scenario where n is very large, but our algorithm is linear after sorting.
Now, is there any alternative that doesn't require sorting? Possibly but not needed.
Thus, solution is done.
But wait, the problem statement mentions "Rearrange these numbers to satisfy |a1 - a2| ≤ |a2 - a3| ≤ … ≤ |a_{n-1} - a_n|". Our construction yields a sequence where differences are non-decreasing. Good.
Now, we must ensure that the sequence is a permutation of original numbers, which it is, since we take all indices exactly once.
Now, let's test with a random case not yet tested: n=7 sorted [1,2,3,4,5,6,7]. mid = (7-1)//2 = 3. So b0 = s[3]=4, b1 = s[4]=5. left=2, right=5. Loop: append s[2]=3, s[5]=6 => now [4,5,3,6]; left=1, right=6; loop: append s[1]=2, s[6]=7 => [4,5,3,6,2,7]; left=0, right=7; exit loop; while left>=0: append s[0]=1 => [4,5,3,6,2,7,1]. Differences: |4-5|=1, |5-3|=2, |3-6|=3, |6-2|=4, |2-7|=5, |7-1|=6. That's 1,2,3,4,5,6 - perfect increasing. Nice! So for consecutive integers, it yields perfect increasing differences.
Now test with non-uniform: n=7 sorted [1,10,20,30,40,50,100]. mid=3 => b0=30, b1=40. left=2 ->20, right=5->50: [30,40,20,50]; left=1->10, right=6->100: [30,40,20,50,10,100]; left=0->1: [30,40,20,50,10,100,1]. Differences: 10,20,30,40,90,99? Compute: |30-40|=10, |40-20|=20, |20-50|=30, |50-10|=40, |10-100|=90, |100-1|=99 -> 10,20,30,40,90,99 non-decreasing. Works.
Thus the construction is solid.
Now, we can present the solution with explanation.
But before final answer, verify that the construction works for n=3 when numbers are not sorted? We sort first.
One more: n=3 [100, -100, 0] sorted [-100,0,100]; mid=1 => [0,100,-100]; differences: 100,200 -> 100<=200 works.
All good.
Now, we should also consider if there is any scenario where absolute value might be needed because we might have negative numbers? Our calculations of differences as larger minus smaller hold because we always compare numbers in sorted order, but after rearrangement, the order may not preserve the sorted order; however we ensure that when we compute the absolute value, the larger minus smaller is valid because we know which is larger based on indices? Let's verify: In our sequence, sometimes we place a smaller number after a larger one, but we always compute absolute value, which is the positive difference. In our difference formulas, we assumed that the later element is larger when needed. But in the sequence, after b2 (which is s[mid+1], the largest among the two middle), we then go to s[left] which is smaller. So the difference is b2 - b3 = s[mid+1] - s[left] (since s[mid+1] >= s[left] because left index < mid+1). Similarly, b3 to b4: s[mid+2] - s[left] because s[mid+2] >= s[left]. b4 to b5: s[mid+2] - s[left-1]? Wait b4 is s[right] which is larger than s[left-1]? Since right index > left-1? Actually s[right] is a later index in sorted order, so s[right] >= s[left-1] because right > left-1. So the subtraction yields positive. So all absolute differences are simply the larger minus smaller because we always alternate between a larger (from right side) and a smaller (from left side) or vice versa? But we need to be sure that every consecutive pair consists of one element from left side (smaller) and one from right side (larger) except possibly the first pair (two middle) where both could be equal. Let's check: The sequence: b1 (mid) and b2 (mid+1). Since sorted, b1 <= b2, so difference = b2 - b1. Then b2 (mid+1) and b3 (left1): left1 index < mid+1, so b2 >= b3, diff = b2 - b3. b3 (left1) and b4 (right1): right1 index > left1, so b4 >= b3, diff = b4 - b3. b4 (right1) and b5 (left2): left2 index < right1, so b4 >= b5, diff = b4 - b5. And so on. So indeed each consecutive pair consists of one element from the right side (larger index) and one from the left side (smaller index), except possibly when we have two middle elements, both could be equal. Also at the very end, if we have an extra left after a right, that pair is right (larger) then left (smaller), so difference = right - left. So always the larger minus smaller. Therefore our formulas using subtraction of sorted values are correct and absolute not needed explicitly.
Thus the proof stands.
Now we can code.
Time complexity: O(n log n) per test case, total O(N log N) where N sum n <= 1e5, which is well within limits.
Memory: O(n) per test case.
Now, confirm with sample input:
Input:
2
6
5 -2 4 8 6 5
4
8 1 4 2
Our algorithm for test case 1: sorted [-2,4,5,5,6,8]; mid=2; ans = [5,5]; left=1->4, right=4->6 => ans [5,5,4,6]; left=0->-2, right=5->8 => ans [5,5,4,6,-2,8] -> output "5 5 4 6 -2 8". That's valid.
Test case 2: sorted [1,2,4,8]; mid=1; ans [2,4]; left=0->1, right=3->8 => ans [2,4,1,8] -> output "2 4 1 8". Sample output is "1 2 4 8". Both are acceptable. The problem says "print any of them". So fine.
Now, just to be thorough, we should also consider whether there is any scenario where the condition might fail due to integer overflow? No, we only compute differences for checking but we don't need to compute them in the solution; we just output the permutation.
Thus we can finalize.
Implementation details in Python:
import sys
def solve():
import sys
input_data = sys.stdin.read().strip().split()
if not input_data:
return
it = iter(input_data)
t = int(next(it))
out_lines = []
for _ in range(t):
n = int(next(it))
a = [int(next(it)) for __ in range(n)]
a.sort()
mid = (n-1)//2
ans = [a[mid], a[mid+1]]
left = mid-1
right = mid+2
while left >= 0 and right < n:
ans.append(a[left])
ans.append(a[right])
left -= 1
right += 1
while left >= 0:
ans.append(a[left])
left -= 1
# while right < n: (should not happen)
# ans.append(a[right])
# right += 1
out_lines.append(' '.join(map(str, ans)))
sys.stdout.write('\n'.join(out_lines))
if name == 'main':
solve()
We must ensure that for n=3, a[mid+1] is valid: yes.
Now, I'd like to test a bit more mentally with n=3 all same: a=[5,5,5] sorted [5,5,5], mid=1, ans=[5,5], left=0, right=3, while left false, then while left: ans.append(5) -> [5,5,5]. OK.
Now, consider n=100000 large, okay.
Thus solution is ready.
We can also propose alternative implementation using deque, but simple indices fine.
Now, I'll produce final answer with explanation in the response. ```python
import sys
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
t = int(next(it))
out_lines = []
for _ in range(t):
n = int(next(it))
a = [int(next(it)) for _ in range(n)]
a.sort()
mid = (n - 1) // 2 # index of the left centre
ans = [a[mid], a[mid + 1]] # first two elements
left = mid - 1
right = mid + 2
# alternate between left and right sides
while left >= 0 and right < n:
ans.append(a[left])
ans.append(a[right])
left -= 1
right += 1
# if any left indices remain (happens only for odd n)
while left >= 0:
ans.append(a[left])
left -= 1
# the right side never has remaining elements, but for safety:
# while right < n:
# ans.append(a[right])
# right += 1
out_lines.append(' '.join(map(str, ans)))
sys.stdout.write('\n'.join(out_lines))
if name == 'main':
solve()