Array With Elements Not Equal to Average of Neighbors
Reorder distinct numbers so that none of them sits exactly halfway between its two neighbours.
You are given an array numsinums[i - 1] + nums[i + 1]2 * nums[i]
Example 1
Output: [1, 4, 2, 5, 3]
Explanation: 4 is bigger than both its neighbours, 2 is smaller than both, and 5 is bigger than both. [1, 2, 4, 5, 3] would also be accepted.
Example 2
Output: [0, 7, 2, 9, 6]
The Idea
The average of two numbers is the point halfway between them: the average of 4 and 6 is 5, and the average of 1 and 3 is 2. This problem asks for an order in which no number sits exactly halfway between the two numbers beside it.
The first and last numbers have only one neighbour each, so they never count. Only the inner numbers, the ones with a neighbour on each side, can break the rule.
Look at Example 1 as it is given, [1, 2, 3, 4, 5]
Halfway between two numbers is always somewhere between them, never above the bigger one and never below the smaller one. So a number that is bigger than both its neighbours cannot be their average, and neither can a number that is smaller than both.
That suggests a shape: low, high, low, high, and so on. Every inner number is then either a peak, higher than both neighbours, or a valley, lower than both. An order like this is called a zigzag.
Look at the picture, which uses Example 2. At the top, the sorted values 0, 2, 6, 7, 9 are split into a smaller half, 0, 2 and 6, and a larger half, 7 and 9. Below, the result [0, 7, 2, 9, 6]
Why does every peak stay above both its neighbours, whatever the numbers are? Because every value in the larger half is bigger than every value in the smaller half. A peak comes from the larger half and its neighbours come from the smaller half, so it is higher than both without the code ever comparing them.
Solution Approach
Trying orders until one works would be slow: n values have n! orders (n × (n - 1) × ... × 1), already 3,628,800 for 10 values. The zigzag needs no search, and building it means settling three things: how to find the two halves, which positions each half fills, and which half gets the extra value when the count is odd.
Finding the two halves
How do we know which values are the small ones? Sorting a copy of the array puts the smallest values first, so the smaller half is the front of the sorted copy and the larger half is the back. The values are distinct, so the last value of the smaller half is strictly below the first value of the larger half, and no peak can tie with a neighbour.
Which positions each half fills
Where does each half go? Counting positions from 0, the smaller half fills the even positions 0, 2, 4, ..., and the larger half fills the odd positions 1, 3, 5, .... Each half is taken in its sorted order, so one pass from left to right with one index into each half is enough. Every odd position then holds a peak, and every inner even position holds a valley.
When the count is odd
What if n is odd? Then there is one more even position than odd ones: for n = 5, positions 0, 2 and 4 against 1 and 3. So the smaller half gets the extra value and has (n + 1) / 2
Java Solution
The method rearrangeArray
- First, copy the input into
and sort the copy, so the input stays as it was. The smaller half is now the front ofsorted , and the larger half is the back.sorted - Keep two indexes into
, one for each half.sorted starts at 0, the start of the smaller half.small starts atlarge , just after the smaller half.(n + 1) / 2 - Fill a new array,
, one position at a time. An even position takes the next value from the smaller half,result , and an odd position takes the next value from the larger half,sorted[small++] .sorted[large++] - When every position is filled, return
.result
To check the answers, the program also has a method isValid(1 + 4) / 2
The main[1, 2, 3, 4, 5]
import java.util.Arrays;
import java.util.Random;
public class ArrayWithElementsNotEqualToAverageOfNeighbors {
public int[] rearrangeArray(int[] nums) {
int n = nums.length;
int[] sorted = nums.clone(); // leave the input as it is
Arrays.sort(sorted);
int[] result = new int[n];
int small = 0; // next value from the smaller half
int large = (n + 1) / 2; // next value from the larger half
for (int i = 0; i < n; i++) {
result[i] = (i % 2 == 0) ? sorted[small++] : sorted[large++];
}
return result;
}
// true if no inner value is the average of its two neighbours
static boolean isValid(int[] a) {
for (int i = 1; i < a.length - 1; i++) {
if ((long) a[i - 1] + a[i + 1] == 2L * a[i]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
ArrayWithElementsNotEqualToAverageOfNeighbors s =
new ArrayWithElementsNotEqualToAverageOfNeighbors();
int[] sortedInput = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(sortedInput) + " valid as given? "
+ isValid(sortedInput));
int[][] tests = {
{1, 2, 3, 4, 5}, // example 1
{6, 2, 0, 9, 7}, // example 2
{10, -3, 8, 0, 4, -1}, // even length, negative values
{3, 1, 2}, // shortest length with an inner value
{5, 1}, // no inner value at all
{7}
};
for (int[] t : tests) {
int[] r = s.rearrangeArray(t);
System.out.println(Arrays.toString(t) + " -> " + Arrays.toString(r)
+ " valid? " + isValid(r));
}
Random rnd = new Random(42);
int bad = 0;
for (int run = 0; run < 10000; run++) {
int[] a = rnd.ints(-1000, 1000).distinct().limit(1 + rnd.nextInt(30)).toArray();
if (!isValid(s.rearrangeArray(a))) {
bad++;
}
}
System.out.println("10000 random arrays, invalid results: " + bad);
}
}
Running it prints:
[1, 2, 3, 4, 5] valid as given? false
[1, 2, 3, 4, 5] -> [1, 4, 2, 5, 3] valid? true
[6, 2, 0, 9, 7] -> [0, 7, 2, 9, 6] valid? true
[10, -3, 8, 0, 4, -1] -> [-3, 4, -1, 8, 0, 10] valid? true
[3, 1, 2] -> [1, 3, 2] valid? true
[5, 1] -> [1, 5] valid? true
[7] -> [7] valid? true
10000 random arrays, invalid results: 0
Look at the first line: the input [1, 2, 3, 4, 5][-3, 4, -1, 8, 0, 10][3, 1, 2][1, 3, 2]
The start of largen / 2[1, 2, 3, 4, 5][1, 3, 2, 4, 3]
The original implementation,
Complexity
Sorting the copy is the most expensive step; everything after it is a single pass over the array.
- Time: O(n log n). Sorting n values costs O(n log n). The loop that fills
visits each position once, which is O(n) and does not change the total.result - Space: O(n).
is a full copy of the input andsorted is the returned array, and each holds n values.result
A zigzag that allows equal neighbours can be built in O(n) without sorting, as in