#526

Beautiful Arrangement

Medium Bitmask DP

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count permutations of 1..n (n ≤ 15) where, at every position i (1-indexed), either the number divides i or i divides the number.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: count arrangements where every position and its number divide one way or the other.

Why this works: the set of numbers already used is a bitmask, and the next position is its popcount + 1. dp[mask] counts the ways.

Example: n = 2

[1, 2] ✓, [2, 1] ✓ → 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Storing the position as part of the state — it's determined by the mask already.

Solve on LeetCode ↗
Complexity
  • Time: O(2^n · n).
  • Space: O(2^n).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon