Skip to problem
←

Beautiful Arrangement

Medium 0 attempts

A beautiful arrangement is a permutation of the integers 1 through n in which, at every 1-based position i, either the value is divisible by i or i is divisible by the value.

Given n, return the number of beautiful arrangements. If you store a permutation in a JavaScript array, the value at position i is perm[i - 1].

Function contract

Implement countArrangement(n), where n is an integer from 1 to 15.

Output: The number of permutations of 1 through n satisfying the divisibility rule at every 1-based position.

Example 1

Input
n = 2
Output
2

Explanation: Both [1,2] and [2,1] satisfy the rule at positions 1 and 2.

Example 2

Input
n = 1
Output
1
Constraints
  • 1 <= n <= 15

Use backtracking to place numbers 1 to n into positions 1 to n. At each position, only place a number if it satisfies the divisibility condition (position divides number or number divides position).

javascript
function countArrangement(n) {
  let count = 0;
  const visited = new Array(n + 1).fill(false);

  function backtrack(pos) {
    if (pos > n) {
      count++;
      return;
    }
    for (let num = 1; num <= n; num++) {
      if (!visited[num] && (num % pos === 0 || pos % num === 0)) {
        visited[num] = true;
        backtrack(pos + 1);
        visited[num] = false;
      }
    }
  }

  backtrack(1);
  return count;
}

Time: O(n × n!) as a loose upper bound, including candidate checks at partial arrangements Space: O(n) for recursion stack and visited array

Loading discussion…

Saved in this browser only. Private to you.

JavaScript