Beautiful Arrangement
Master this topic with zero to advance depth.
Beautiful Arrangement
The divisibility Rule
An arrangement is beautiful if for every position (1-indexed):
perm[i] % i == 0ORi % perm[i] == 0
Pruning in Backtracking
Instead of generating all permutations and checking them, we check the condition at each step. If a number cannot be placed at the current index, we prune the entire branch.
Count the number of beautiful arrangements of numbers 1 to N. Includes visual placement trace.
Examples
Input: n = 2
Output: 2
Approach 1
Level I: Backtracking with Pruning
Intuition
Try placing each available number in the current position, checking the rule.
Use a visited array to track used numbers. At each position idx, iterate from 1 to N. If i is not used and satisfies the beautiful rule, place it and recurse.
âą O(K) where K is the number of valid permutations.đž O(N)
Detailed Dry Run
N=3
1. Pos 1: Try 1 (1%1==0). OK.
2. Pos 2: Try 2 (2%2==0). OK.
3. Pos 3: Try 3 (3%3==0). OK. (Result=1)
4. Pos 2: Try 3 (3%2!=0, 2%3!=0). Fail.Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.