Array With Elements Not Equal to Average of Neighbors
You are given a 0-indexed array nums
More formally, the rearranged array should have the property such that for every i1 <= i < nums.length - 1(nums[i-1] + nums[i+1]) / 2
Return any rearrangement of nums
Example 1
Output: [1,2,4,5,3]
Explanation: When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
Example 2
Output: [9,7,6,2,0]
Explanation: When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.
Constraints:
3 <= nums.length <= 1050 <= nums[i] <= 105
Solution 1 - Sort and rearrange elements
The main intution behind this solution is, say if we were given the input array as [1, 2, 3, 4, 5, 6](1, 3)
Consider, above example nums = [1, 2, 3, 4, 5, 6][1, _, 2, _, 3, _][1, 6, 2, 5, 3, 4]
Note: Before we apply the solution, we are going to sort the array first, so that they are either in increasing or decreasing order and we will rearrange number as shown above.
import java.util.Arrays;
public class ArrayWithElementsNotEqualToAverageOfNeighbors {
static int[] rearrangeArray(int[] nums) {
Arrays.sort(nums);
int l=0;
int r = nums.length-1;
int[] res = new int[nums.length];
int index = 0;
while(l<=r) {
res[index++] = nums[l++];
if(l<=r){ // to handle odd length arrays
res[index++] = nums[r--];
}
}
return res;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(rearrangeArray(new int[]{1, 2, 3, 4, 5})));
System.out.println(Arrays.toString(rearrangeArray(new int[]{1, 2, 3, 4, 5, 6})));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n log n) time where nnums
Space complexity: O(n) for the result array.
Above implementations source code can be found at