Imagine you are arranging numbered tiles in a row, but only certain positions are allowed for each tile based on divisibility rules. How many beautiful arrangements can you create?
Given an integer n, count the number of the beautiful arrangements that you can construct. A beautiful arrangement is defined as an array of the numbers from 1 to n such that for every position i (1-indexed), either the number at position i is divisible by i or i is divisible by the number.
1 ≤ n ≤ 15
Edge cases: n = 1 → output: 1 (only one number, trivially beautiful)n = 0 → output: 0 (no numbers, no arrangements)n = 15 → output: large number, tests efficiency
def countArrangement(n: int) -> int:public int countArrangement(int n)int countArrangement(int n)function countArrangement(n)
def countArrangement(n: int) -> int:
# Write your solution here
pass
class Solution {
public int countArrangement(int n) {
// Write your solution here
return 0;
}
}
#include <vector>
using namespace std;
int countArrangement(int n) {
// Write your solution here
return 0;
}
function countArrangement(n) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: 0Returning 0 for all inputs due to missing base case or incorrect initialization.✅ Add explicit base case: if n == 0: return 0; initialize count properly.
Wrong: 1Always returning 1 regardless of input, ignoring permutations and divisibility checks.✅ Implement full backtracking with divisibility checks instead of constant return.
Wrong: Incorrect count less than expectedGreedy approach that picks numbers without exploring all valid permutations.✅ Use backtracking with pruning instead of greedy selection.
Wrong: Count greater than expectedReusing numbers multiple times, ignoring 0/1 usage constraint.✅ Track used numbers with boolean array or bitmask to avoid reuse.
Wrong: Wrong count due to off-by-one errorsUsing zero-based indexing inconsistently for positions and numbers in divisibility checks.✅ Use 1-based indexing consistently for positions and numbers.