Beautiful Arrangement (LeetCode 526): Solution and Explanation

Medium
Array
Dynamic Programming
Backtracking
Bit Manipulation
Bitmask

Count the permutations of 1..n where, at every 1-indexed position i, the number placed there divides i or is divisible by i. For n = 2 both [1,2] and [2,1] work, so the answer is 2. The limit is n <= 15.

Intuition

Think of an n by n board with positions as rows and numbers as columns. A cell is allowed when one of its two labels divides the other. A beautiful arrangement picks exactly one allowed cell in every row and every column.

Backtracking fills one row at a time and only uses allowed cells in unused columns, so invalid permutations are cut off as soon as one position fails.

Rows with large labels have very few allowed cells (position 11 accepts only 1 and 11). Filling from position n down to 1 makes the search hit those tight rows first, which prunes the tree much earlier.

Approach: Backtracking from the last position

  1. Keep a boolean array used for the numbers 1..n.
  2. Define place(pos). If pos == 0, every position is filled, so return 1.
  3. Otherwise, for each unused num with num % pos == 0 or pos % num == 0, mark it used, add place(pos - 1) to a running count, and unmark it.
  4. Return the count; the answer is place(n).

Step-by-step example

n = 2
  1. Position 2 accepts 1 (2 is divisible by 1) and 2 (2 divides 2).
  2. Place 1 at position 2. Position 1 accepts any number, so 2 goes there: arrangement [2,1].
  3. Undo, then place 2 at position 2. Position 1 takes 1: arrangement [1,2].
  4. No other number fits position 2, so the total is 2.

Code: Python, Java, C++

1class Solution:
2    def countArrangement(self, n: int) -> int:
3        used = [False] * (n + 1)
4        def place(pos):
5            if pos == 0:
6                return 1
7            count = 0
8            for num in range(1, n + 1):
9                if not used[num] and (num % pos == 0 or pos % num == 0):
10                    used[num] = True
11                    count += place(pos - 1)
12                    used[num] = False
13            return count
14        return place(n)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(k)

k is the number of valid partial arrangements the search visits, which is far below n! thanks to pruning (a few thousand for n = 11).

Space

O(n)

The recursion depth and the used array are both n.

Other approaches

Bitmask DP (time O(n * 2^n), space O(2^n))

Let dp[mask] be the number of ways to fill positions 1..popcount(mask) with exactly the numbers in mask. Extend each mask by any number that fits the next position.

Generate all permutations (time O(n! * n), space O(n))

Enumerate every permutation and check the rule at the end. It is correct but n! grows too fast past n = 10.

Common mistakes

  • Using 0-based positions. The rule is defined on 1-based positions, and position 0 would make every modulo check meaningless.
  • Checking the rule only once the permutation is complete. Without pruning at each placement the search explodes.
  • Forgetting to unmark the number after the recursive call, which silently blocks it from every later branch.

Frequently asked questions

Why does filling from n down to 1 help?

High positions accept few numbers, so placing them first discards dead branches near the root. Position 1 accepts every number, so leaving it for last costs nothing.

Is the answer symmetric in some way?

Yes. The rule is symmetric between a position and the number placed there, so the inverse of a beautiful arrangement is also beautiful. The counting itself does not need this fact.

When should I prefer the bitmask DP?

When n is at the upper limit and you want a guaranteed bound. Both approaches pass for n <= 15, and the backtracking version is easier to explain in an interview.