Beautiful Arrangement

Count the orders of 1 to n in which every number and its position divide one another.

Place the numbers 1 to n in positions 1 to n, each number once. Such an order is beautiful if, at every position, the number there is divisible by the position, or the position is divisible by the number. Given n, return how many beautiful orders exist.

Example 1
Input: n = 2
Output: 2
Explanation: [1, 2] works, because 1 is divisible by 1 and 2 by 2. [2, 1] works too: position 1 holds 2, which is divisible by 1, and position 2 holds 1, and 2 is divisible by 1.
Example 2
Input: n = 1
Output: 1
Example 3
Input: n = 3
Output: 3
Explanation: the beautiful orders are [1, 2, 3], [2, 1, 3] and [3, 2, 1].
Solution

The Idea

Picture three cards, numbered 1, 2 and 3, and a row of three slots, numbered 1, 2 and 3, which the problem calls positions. Each card goes into one slot, and a card may only sit in a slot when one of the two numbers divides the other. There are six ways to lay the cards out, and Example 3 says three of them follow the rule.

Take [1, 3, 2]. Card 1 in slot 1 is fine, since every number is divisible by 1. Card 3 in slot 2 is not: 3 is not divisible by 2, and 2 is not divisible by 3. So [1, 3, 2] fails at position 2, and card 2 in slot 3 never gets a say.

Checking all six orders is easy here. For n = 15, though, there are 15! orders, about 1.3 trillion. Is there a way to throw out many orders at once, without looking at each?

There is, because a failure happens at one position. Once 3 sits at position 2 after 1, no choice for position 3 can repair it. So fill the positions one at a time, from position 1 onward, and drop a number the moment it does not fit. Look at the picture below.

The choice tree for n = 3. Position 1 takes 1, 2 or 3. 3 at position 2 is cut short twice, and 2 at position 3 is cut short once. Three branches reach the bottom row, labelled beautiful: [1, 2, 3], [2, 1, 3] and [3, 2, 1].

Each row of the picture is a position, and each blue box is the number placed there. Position 1 takes 1, 2 or 3. Under 1, position 2 can take 2, because 2 is divisible by 2. It cannot take 3, and the orange dashed box labelled "cut short" marks where that branch stops. The same happens under 2.

Under 3, position 2 can take 1 or 2. After 3 and 1, the number left is 2, and 2 at position 3 is cut short as well. Three branches reach the bottom row, labelled "beautiful": [1, 2, 3], [2, 1, 3] and [3, 2, 1]. That is the answer 3.

Follow the left side of the picture. After [1, 2, 3] is complete, position 3 has no other number to try. Position 2 tries 3, which is cut short. So the search steps back to position 1, gives back the 1 it placed there, and puts 2 there instead. Building an order position by position, and stepping back to the last position with a number still to try, is called backtracking.

Solution Approach

Turning that idea into code means settling three things: which numbers a position may take, how to remember which numbers are already placed, and how to count the finished orders. One more change, filling the positions from the back, is optional and makes the search faster.

Numbers a position may take

At position pos, which numbers are worth trying? A number num must not be placed already, and it must pass the rule num % pos == 0 || pos % num == 0. Here num % pos is the remainder of num divided by pos, so 0 means pos divides num, and pos % num == 0 checks the other way round.

Some positions are much pickier than others. Position 1 accepts every number, while for n = 15, position 7 accepts only 1, 7 and 14. Each number turned away there removes every order that would have continued from it.

Remembering which numbers are placed

How does a position know which numbers are taken? A boolean array named used answers that. It has n + 1 entries, so used[num] works for the numbers 1 to n directly, and entry 0 is never read.

Before moving on to the next position, the search sets used[num] to true. When it steps back, it sets it to false again, so the next number tried at this position, and every branch after it, finds num free.

Counting the finished orders

The problem asks only how many beautiful orders exist, so nothing needs to be stored. A method place fills position pos and then calls itself to fill position pos + 1. It returns how many ways the remaining positions can be filled.

When pos is past n, every position holds a number, which is one beautiful order, so the call returns 1. Any other call adds up what its tries return. In the picture, the 3 at position 1 gets 0 from the 1 below it and 1 from the 2, so it returns 1.

Filling from the back (optional)

Could the search find dead ends sooner? The large positions accept the fewest numbers, so filling the positions from n down to 1 cuts branches closer to the top of the tree. For n = 15, a version that fills from the back makes 102,376 calls to place, against 747,961 for filling from the front, with the same count of 24,679.

Java Solution

The method countArrangement works in these steps:

  1. First, create used, a boolean array of n + 1 entries that all start as false, and call place(n, 1, used) to fill the positions from position 1.
  2. In place, if pos is greater than n, every position is filled, so return 1 for this beautiful order.
  3. Otherwise, set count to 0 and loop num from 1 to n. Try a number only if used[num] is false and num % pos == 0 || pos % num == 0.
  4. For a number that fits, set used[num] to true, add the result of place(n, pos + 1, used) to count, and then set used[num] back to false.
  5. When the loop has tried every number, return count.

The main method runs the three examples, then n = 4 and n = 15.

Java
public class BeautifulArrangement {

    public static int countArrangement(int n) {
        return place(n, 1, new boolean[n + 1]);
    }

    // Fill position pos (1-based) with every unused number that fits, then the next position
    private static int place(int n, int pos, boolean[] used) {
        if (pos > n) {
            return 1;                                   // every position is filled
        }
        int count = 0;
        for (int num = 1; num <= n; num++) {
            if (!used[num] && (num % pos == 0 || pos % num == 0)) {
                used[num] = true;                       // take num for this position
                count += place(n, pos + 1, used);       // fill the positions after it
                used[num] = false;                      // give num back for the next try
            }
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println("n = 2: " + countArrangement(2));
        System.out.println("n = 1: " + countArrangement(1));
        System.out.println("n = 3: " + countArrangement(3));
        System.out.println("n = 4: " + countArrangement(4));
        System.out.println("n = 15: " + countArrangement(15));
    }
}

Running it prints:

Output
n = 2: 2
n = 1: 1
n = 3: 3
n = 4: 8
n = 15: 24679

The first three lines match the examples: 2, 1 and 3. Look at the line for n = 4: 8 of the 24 orders of four numbers are beautiful. The last line, 24679 for n = 15, took 747,961 calls to place, far fewer than the 1.3 trillion orders of 15 numbers.

The line used[num] = false matters more than it looks. Without it, every number stays taken after its first branch. Only [1, 2, ..., n], with each number at its own position, is ever finished, and the method returns 1 for every n from 1 to 6, including 1 instead of 8 for n = 4.

Complexity

The work is the number of calls to place. In the picture that is one call for the start box and one for each blue box, 11 calls for n = 3; the orange boxes are turned away before any call.

  • Time: at most O(n ยท n!), because without the divisibility rule the tree would reach all n! orders, and each call loops over all n numbers; the rule cuts most branches, so n = 15 needs 747,961 calls.
  • Space: O(n), because used has n + 1 entries and the calls go n + 1 deep, one per position plus the one that finds pos past n.