Beautiful Arrangement (LeetCode 526): Solution and Explanation
Count the permutations of 1..n where, at every 1-indexed position i, the number placed there divides i or is divisible by i. For n = 2 both [1,2] and [2,1] work, so the answer is 2. The limit is n <= 15.
Intuition
Think of an n by n board with positions as rows and numbers as columns. A cell is allowed when one of its two labels divides the other. A beautiful arrangement picks exactly one allowed cell in every row and every column.
Backtracking fills one row at a time and only uses allowed cells in unused columns, so invalid permutations are cut off as soon as one position fails.
Rows with large labels have very few allowed cells (position 11 accepts only 1 and 11). Filling from position n down to 1 makes the search hit those tight rows first, which prunes the tree much earlier.
Approach: Backtracking from the last position
- Keep a boolean array
usedfor the numbers 1..n. - Define
place(pos). Ifpos == 0, every position is filled, so return 1. - Otherwise, for each unused
numwithnum % pos == 0orpos % num == 0, mark it used, addplace(pos - 1)to a running count, and unmark it. - Return the count; the answer is
place(n).
Step-by-step example
n = 2
- Position 2 accepts 1 (2 is divisible by 1) and 2 (2 divides 2).
- Place 1 at position 2. Position 1 accepts any number, so 2 goes there: arrangement [2,1].
- Undo, then place 2 at position 2. Position 1 takes 1: arrangement [1,2].
- No other number fits position 2, so the total is 2.
Code: Python, Java, C++
1class Solution:
2 def countArrangement(self, n: int) -> int:
3 used = [False] * (n + 1)
4 def place(pos):
5 if pos == 0:
6 return 1
7 count = 0
8 for num in range(1, n + 1):
9 if not used[num] and (num % pos == 0 or pos % num == 0):
10 used[num] = True
11 count += place(pos - 1)
12 used[num] = False
13 return count
14 return place(n)1class Solution {
2 private boolean[] used;
3 private int n;
4
5 public int countArrangement(int n) {
6 this.n = n;
7 used = new boolean[n + 1];
8 return place(n);
9 }
10
11 private int place(int pos) {
12 if (pos == 0) {
13 return 1;
14 }
15 int count = 0;
16 for (int num = 1; num <= n; num++) {
17 if (!used[num] && (num % pos == 0 || pos % num == 0)) {
18 used[num] = true;
19 count += place(pos - 1);
20 used[num] = false;
21 }
22 }
23 return count;
24 }
25}1class Solution {
2public:
3 int countArrangement(int n) {
4 vector<bool> used(n + 1, false);
5 return place(n, n, used);
6 }
7
8 int place(int pos, int n, vector<bool>& used) {
9 if (pos == 0) {
10 return 1;
11 }
12 int count = 0;
13 for (int num = 1; num <= n; num++) {
14 if (!used[num] && (num % pos == 0 || pos % num == 0)) {
15 used[num] = true;
16 count += place(pos - 1, n, used);
17 used[num] = false;
18 }
19 }
20 return count;
21 }
22};Time and space complexity
O(k)
k is the number of valid partial arrangements the search visits, which is far below n! thanks to pruning (a few thousand for n = 11).
O(n)
The recursion depth and the used array are both n.
Other approaches
Bitmask DP (time O(n * 2^n), space O(2^n))
Let dp[mask] be the number of ways to fill positions 1..popcount(mask) with exactly the numbers in mask. Extend each mask by any number that fits the next position.
Generate all permutations (time O(n! * n), space O(n))
Enumerate every permutation and check the rule at the end. It is correct but n! grows too fast past n = 10.
Common mistakes
- Using 0-based positions. The rule is defined on 1-based positions, and position 0 would make every modulo check meaningless.
- Checking the rule only once the permutation is complete. Without pruning at each placement the search explodes.
- Forgetting to unmark the number after the recursive call, which silently blocks it from every later branch.
Frequently asked questions
Why does filling from n down to 1 help?
High positions accept few numbers, so placing them first discards dead branches near the root. Position 1 accepts every number, so leaving it for last costs nothing.
Is the answer symmetric in some way?
Yes. The rule is symmetric between a position and the number placed there, so the inverse of a beautiful arrangement is also beautiful. The counting itself does not need this fact.
When should I prefer the bitmask DP?
When n is at the upper limit and you want a guaranteed bound. Both approaches pass for n <= 15, and the backtracking version is easier to explain in an interview.