Beautiful Arrangement
Count the orders of 1 to n in which every number and its position divide one another.
Place the numbers 1 to nnn
Example 1
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
Output: 1
Example 3
Output: 3
Explanation: the beautiful orders are [1, 2, 3], [2, 1, 3] and [3, 2, 1].
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
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.
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 posnumnum % pos == 0 || pos % num == 0num % posnumposposnumpos % num == 0
Some positions are much pickier than others. Position 1 accepts every number, while for n = 15
Remembering which numbers are placed
How does a position know which numbers are taken? A booleanusedn + 1used[num]n
Before moving on to the next position, the search sets used[num]truefalsenum
Counting the finished orders
The problem asks only how many beautiful orders exist, so nothing needs to be stored. A method placepospos + 1
When posn
Filling from the back (optional)
Could the search find dead ends sooner? The large positions accept the fewest numbers, so filling the positions from nn = 15place
Java Solution
The method countArrangement
- First, create
, aused array ofboolean entries that all start asn + 1 , and callfalse to fill the positions from position 1.place(n, 1, used) - In
, ifplace is greater thanpos , every position is filled, so return 1 for this beautiful order.n - Otherwise, set
to 0 and loopcount from 1 tonum . Try a number only ifn isused[num] andfalse .num % pos == 0 || pos % num == 0 - For a number that fits, set
toused[num] , add the result oftrue toplace(n, pos + 1, used) , and then setcount back toused[num] .false - When the loop has tried every number, return
.count
The mainn = 4n = 15
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:
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 = 4n = 15place
The line used[num] = falsenn = 4
Complexity
The work is the number of calls to placen = 3
- 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
needs 747,961 calls.n = 15 - Space: O(n), because
hasused entries and the calls gon + 1 deep, one per position plus the one that findsn + 1 pastpos .n