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 nums of distinct integers. Rearrange it so that no value, apart from the first and the last, equals the average of the two values next to it. In other words, for every inner position i, nums[i - 1] + nums[i + 1] must not equal 2 * nums[i]. Return any arrangement that works.

Example 1
Input: nums = [1, 2, 3, 4, 5]
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
Input: nums = [6, 2, 0, 9, 7]
Output: [0, 7, 2, 9, 6]
Solution

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]. The 2 sits between 1 and 3, and it is exactly their average. The same holds for 3, between 2 and 4, and for 4, between 3 and 5. Every inner number breaks the rule. How can we move the numbers so that none of them lands halfway?

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.

The sorted values 0, 2, 6, 7, 9 split into a smaller half 0, 2, 6 and a larger half 7, 9. The result 0, 7, 2, 9, 6 alternates between the halves, so the values go up and down at every step.

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] takes a value from the smaller half, then one from the larger half, and so on. The line goes up and down at every step. The 7 at position 1 is above both 0 and 2, so it cannot be their average. The 2 at position 2 is below both 7 and 9.

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 values. Java's integer division drops the remainder, so this is 3 for n = 5, and also 3 for n = 6, an even split.

Java Solution

The method rearrangeArray works in these steps:

  1. First, copy the input into sorted and sort the copy, so the input stays as it was. The smaller half is now the front of sorted, and the larger half is the back.
  2. Keep two indexes into sorted, one for each half. small starts at 0, the start of the smaller half. large starts at (n + 1) / 2, just after the smaller half.
  3. Fill a new array, result, one position at a time. An even position takes the next value from the smaller half, sorted[small++], and an odd position takes the next value from the larger half, sorted[large++].
  4. When every position is filled, return result.

To check the answers, the program also has a method isValid. It returns true if no inner value is the average of its neighbours, by comparing the sum of the neighbours with twice the value, so nothing is divided. Dividing ints would drop the remainder: (1 + 4) / 2 is 2 in Java.

The main method first checks the input [1, 2, 3, 4, 5] as it is, then rearranges both examples and a few edge cases and checks each result, and finally checks 10,000 random arrays of distinct values.

Java
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:

Output
[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] fails the check, as the walk through Example 1 showed. The next two lines are the two examples, and both match the outputs given above. The even-length array with negative values becomes [-3, 4, -1, 8, 0, 10]: the smaller half, -3, -1 and 0, sits at positions 0, 2 and 4, with 4, 8 and 10 between them. [3, 1, 2] becomes [1, 3, 2], with 3 as its only peak. Arrays of one or two values have no inner value, so any order passes. The last line shows that none of the 10,000 random arrays gave an invalid result.

The start of large is easy to get wrong. Starting it at n / 2 gives the same split for even lengths, but for [1, 2, 3, 4, 5] it starts at index 2, the 3, which belongs to the smaller half. The result is then [1, 3, 2, 4, 3]: 3 appears twice and 5 is lost.

The original implementation, ArrayWithElementsNotEqualToAverageOfNeighbors.java, is on GitHub.

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 result visits each position once, which is O(n) and does not change the total.
  • Space: O(n). sorted is a full copy of the input and result is the returned array, and each holds n values.

A zigzag that allows equal neighbours can be built in O(n) without sorting, as in Wiggle Sort.