Beautiful Arrangement - Problem
Imagine you're arranging n unique numbers from 1 to n in a special way! A beautiful arrangement is a permutation where every position follows a harmonious rule: either the number divides its position, or the position divides the number.
For example, if n = 2, the arrangement [1, 2] is beautiful because:
• Position 1: number 1 divides position 1 ✓
• Position 2: number 2 divides position 2 ✓
Your mission is to count how many beautiful arrangements are possible for a given n. This is a classic
For example, if n = 2, the arrangement [1, 2] is beautiful because:
• Position 1: number 1 divides position 1 ✓
• Position 2: number 2 divides position 2 ✓
Your mission is to count how many beautiful arrangements are possible for a given n. This is a classic
backtracking problem that challenges you to explore all valid permutations efficiently! Input & Output
example_1.py — Simple Case
$
Input:
n = 2
›
Output:
2
💡 Note:
For n=2, we have numbers [1,2] and positions [1,2]. Valid arrangements: [1,2] (1%1=0, 2%2=0) and [2,1] (2%1=0, 1%2≠0 but 2%1=0). Both work!
example_2.py — Medium Case
$
Input:
n = 3
›
Output:
3
💡 Note:
For n=3, valid arrangements are [1,2,3], [2,1,3], and [3,2,1]. For example, [1,2,3]: pos1 has 1 (1%1=0✓), pos2 has 2 (2%2=0✓), pos3 has 3 (3%3=0✓).
example_3.py — Edge Case
$
Input:
n = 1
›
Output:
1
💡 Note:
For n=1, there's only one arrangement [1] at position [1]. Since 1%1=0, this is beautiful. Count = 1.
Visualization
Tap to expand
Understanding the Visualization
1
Start at Position 1
Try placing each number 1 to n at position 1, checking divisibility
2
Move to Next Position
For each valid placement, recurse to the next position with remaining numbers
3
Prune Invalid Branches
If no number works at current position, backtrack immediately
4
Count Complete Arrangements
When all positions are filled, increment the solution counter
Key Takeaway
🎯 Key Insight: Backtracking with constraint checking allows us to eliminate entire branches of invalid arrangements early, making the algorithm much faster than brute force permutation generation.
Time & Space Complexity
Time Complexity
O(n! × n)
Generate n! permutations, check n positions for each
⚠ Quadratic Growth
Space Complexity
O(n)
Space for current permutation and recursion stack
⚡ Linearithmic Space
Constraints
- 1 ≤ n ≤ 15
- The answer is guaranteed to fit in a 32-bit integer
- For n > 10, brute force approaches will timeout
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code