Community Problem

Beautiful Arrangement

Difficulty: Medium

Count the permutations of 1..n where every i either divides perm[i] or is divided by perm[i], using backtracking with divisibility pruning.

Beautiful Arrangement

Count the permutations of 1..n where every i either divides perm[i] or is divided by perm[i], using backtracking with divisibility pruning.

MEDIUM
Free
backtracking
math
recursion
ethandubois

By @ethandubois

December 2, 2025

·

Updated May 18, 2026

207 views

6

4.4 (9)

I had this on a Stripe phone screen and the trick that unlocked it was placing positions in REVERSE order: positions with fewer divisors get filled first, which prunes the tree faster than left-to-right placement. Naive permutation enumeration is n!, but the divisibility constraint kills most branches; the catalog covered permutations, but it skipped this constraint-driven variant.

Beautiful Arrangement

A permutation perm of integers 1..n is called beautiful if for every index i in 1..n (1-indexed), at least one of the following holds:

  • perm[i] is divisible by i, OR
  • i is divisible by perm[i].

Given an integer n, return the number of beautiful arrangements.

Examples

Example 1:

  • Input: n = 1
  • Output: 1
  • Explanation: The only permutation is [1], and 1 | 1 holds.

Example 2:

  • Input: n = 2
  • Output: 2
  • Explanation: [1, 2] and [2, 1] both satisfy the condition at every index.

Example 3:

  • Input: n = 4
  • Output: 8
  • Explanation: Eight of the 24 permutations of 1..4 are beautiful, including [2, 1, 3, 4] (check: 2|2, 1|2, 3|3, 4|4).

Example 4:

  • Input: n = 15
  • Output: 24679
  • Explanation: A non-trivial count that exercises the pruning logic.

Constraints

  • 1 <= n <= 15.

Follow-up

Why fill positions back-to-front? Position i near n typically has fewer values that satisfy value % i == 0 || i % value == 0 (large i rejects most value < i). Fewer candidates means narrower branching at the top of the search tree, where pruning has the biggest payoff.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems