Skip to content
Problem 526 · LeetCode 526(opens in a new tab)

Beautiful Arrangement

MediumBacktracking

Take the numbers 1 to n and put them in a row, using each exactly once. Number the positions 1 to n as well. The row is beautiful if, at every position, the number there and the position divide one another one way or the other: the number is a multiple of the position, or the position is a multiple of the number.

Given n, return how many different beautiful rows there are.

Example 1

Input:  n = 3
Output: 3
Why:    [1, 2, 3], [2, 1, 3] and [3, 2, 1] work
2 more examples and the constraints

Example 2

Input:  n = 4
Output: 8
Why:    of the 24 rows of 1 to 4, eight pass at every position

Example 3

Input:  n = 1
Output: 1
Why:    [1] works: 1 divides 1

Constraints

  • 1 ≤ n ≤ 15

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Backtracking with pruningO(n!)
  2. Bitmask DP over used setsO(n · 2ⁿ)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 15Verdict
Backtracking with pruningO(n!)
Passes; easy to write
Bitmask DP over used setsO(n · 2ⁿ)
Best; a firm bound

n = how many numbers. Work is a rough estimate: pruning makes backtracking far faster than n! suggests.

Edge cases to test

  • n = 1. [1] is the only row, and it works: the answer is 1.
  • Number 1 fits anywhere. Every position is a multiple of 1, so 1 can go in any spot.
  • Position 1 takes anything. Every number is a multiple of 1.
  • Large primes. For n = 13, the number 13 only fits at position 1 or 13, which prunes hard.
  • n = 15. The answer is 24,679 and fits easily in an int.

Common mistakes

  • Checking only that the number divides the position, and missing the other direction.
  • Forgetting to unmark a number after the recursive call, so later branches think it is still used.
  • Using 0-based positions, so the divisibility test runs against the wrong position.

How to talk through it

  1. 1Clarify. Positions start at 1? Does either direction of divisibility count? How large can n get?
  2. 2Start with backtracking. Fill positions in order and prune numbers that do not fit; say the worst case is O(n!).
  3. 3Spot the repeated work. Different orders of the same used numbers leave the same subproblem.
  4. 4Code the bitmask DP. ways[mask] sums ways[mask without x] for each x that fits at position popcount(mask).
  5. 5Test out loud. Check n = 1, n = 3 gives 3, and say n = 15 gives 24,679.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?