Beautiful Arrangement
Difficulty: Medium · Pattern: Backtracking · LeetCode #526
A permutation perm of 1..n is beautiful if for every position i (1-indexed), perm[i] % i == 0 or i % perm[i] == 0. Return the number of beautiful arrangements.
Examples
text
n = 2 → 2 ([1,2] and [2,1])
n = 1 → 1
n = 3 → 3Hints
- Backtrack position by position, placing an unused number that satisfies the divisibility rule.
- Large positions have few compatible numbers. Filling from
ndownward prunes much sooner.
Approach
bt(pos, mask): if pos == 0, count 1. Otherwise for each unused x with x % pos == 0 or pos % x == 0, recurse with bt(pos − 1, mask | bit(x)).
Memoizing on mask alone works too, because pos is determined by the number of bits set. That gives O(n · 2ⁿ) worst case, but the pruned backtracking is already fast for n ≤ 15.
Complexity
Time: O(n · 2ⁿ) with memo; far less in practice due to pruning. Space: O(2ⁿ).
Python solution
from functools import lru_cache
def countArrangement(n):
@lru_cache(maxsize=None)
def bt(pos, mask):
if pos == 0:
return 1
total = 0
for x in range(1, n + 1):
if not mask >> x & 1 and (x % pos == 0 or pos % x == 0):
total += bt(pos - 1, mask | 1 << x)
return total
return bt(n, 0)JavaScript solution
function countArrangement(n) {
const used = new Array(n + 1).fill(false);
const bt = (pos) => {
if (pos === 0) return 1;
let total = 0;
for (let x = 1; x <= n; x++) {
if (used[x] || (x % pos && pos % x)) continue;
used[x] = true; total += bt(pos - 1); used[x] = false;
}
return total;
};
return bt(n);
}