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 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
Beautiful Arrangement BacktrackingThe Challenge: Place numbers 1,2,3 in positions where they "harmonize"Rule: Either number divides position OR position divides numberExample: Position 2 can hold numbers 1,2 (1÷2≠0 but 2÷1=0✓, 2÷2=0✓)Backtracking Tree (n=3)ROOT1→P12→P13→P12→P23→P21→P2✗ Pruned: 3÷2≠0, 2÷3≠0Key Insight: Early pruning saves massive computation!Instead of checking 3! = 6 full permutations, we eliminate invalid paths immediatelyFinal count: 3 beautiful arrangements found efficiently
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

n
2n
Quadratic Growth
Space Complexity
O(n)

Space for current permutation and recursion stack

n
2n
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
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
89.2K Views
Medium Frequency
~15 min Avg. Time
2.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