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: 3
💡 Note: Valid arrangements are [1,2,3], [2,1,3], and [3,2,1]. For [1,2,3]: 1%1=0, 2%2=0, 3%3=0. For [2,1,3]: 2%1=0, 1%2≠0 but 2%1=0, 3%3=0. For [3,2,1]: 3%1=0, 2%2=0, 1%3≠0 but 3%1=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 INPUT n = 2 integers: {1, 2} 1 2 pos 1 pos 2 Beautiful Condition: perm[i] % i == 0 OR i % perm[i] == 0 Input: n = 2 Find all perms ALGORITHM STEPS 1 Backtracking Setup Track used numbers 2 Try Position 1 1%1=0 OK, 2%1=0 OK 3 Try Position 2 Check divisibility 4 Count Valid Perms Increment counter Permutation Check: [1,2] OK [2,1] OK 1%1=0, 2%2=0 2%1=0, 1%1=0 FINAL RESULT Beautiful Arrangements: 1 2 OK 2 1 OK Output: 2 Both permutations satisfy the condition! Time: O(k), k = valid perms Space: O(n) Key Insight: Use backtracking to explore all permutations. At each position i, only try numbers that satisfy the divisibility condition (num % i == 0 OR i % num == 0). This prunes invalid branches early and efficiently counts all beautiful arrangements without generating all n! permutations. TutorialsPoint - Beautiful Arrangement | Optimal Backtracking Solution
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