Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true:

  • perm[i] is divisible by i
  • i is divisible by perm[i]

Given an integer n, return the number of the beautiful arrangements that you can construct.

Input & Output

Example 1 — Small Case
$ Input: n = 2
Output: 2
💡 Note: Both [1,2] and [2,1] are beautiful: 1%1=0, 2%2=0 for first; 2%1=0, 1%2≠0 but 2%1=0 for second
Example 2 — Moderate Case
$ Input: n = 3
Output: 2
💡 Note: Valid arrangements are [2,1,3] and [3,2,1]. For [2,1,3]: 2%1=0, 1%2≠0 but 2%1=0, 3%3=0. All conditions satisfied.
Example 3 — Single Element
$ Input: n = 1
Output: 1
💡 Note: Only arrangement [1] where 1%1=0, so it's beautiful

Constraints

  • 1 ≤ n ≤ 15

Visualization

Tap to expand
Beautiful Arrangement Problem (n=3)Find permutations where perm[i] % i == 0 OR i % perm[i] == 0Input: n = 3Numbers: [1, 2, 3]Positions: [1, 2, 3]Check Arrangements[2,1,3]: 2%1=0, 1%2≠0 but 2%1=0, 3%3=0 ✓[3,2,1]: 3%1=0, 2%2=0, 1%3≠0 but 3%1=0 ✓Output: 3Valid arrangements:[1,2,3], [2,1,3], [3,2,1]Position Rules:Pos 1Pos 2Pos 3val%1=0 OR1%val=0val%2=0 OR2%val=0val%3=0 OR3%val=0Invalid Examples:[1,3,2]: 3%2≠0 and 2%3≠0 ✗[2,3,1]: 3%2≠0 and 2%3≠0 ✗🎯 Key Insight: Use backtracking to build valid arrangements position by position
Understanding the Visualization
1
Input
Integer n representing range [1,2,...,n]
2
Check Rule
For each position i, either perm[i] % i == 0 OR i % perm[i] == 0
3
Count Valid
Return total number of beautiful arrangements
Key Takeaway
🎯 Key Insight: Backtracking with early pruning eliminates invalid arrangements without full exploration
Asked in
Google 15 Microsoft 12 Amazon 8
89.0K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen