oneby7

Recursion and Backtracking Searching with constraints

335. Beautiful Arrangement

Medium

You are given an integer n. Arrange the numbers 1 to n in a row of n positions, one number per position. The positions are numbered from 1 to n, left to right.

An arrangement is beautiful when every number fits its position. The number at position i fits when it is a multiple of i, or when i is a multiple of it. One of the two is enough.

Return how many beautiful arrangements there are.

Example 1

Input: n = 4

Output: 8

Explanation: The eight are [1,2,3,4], [1,4,3,2], [2,1,3,4], [2,4,3,1], [3,2,1,4], [3,4,1,2], [4,1,3,2] and [4,2,3,1]. In [2,4,3,1], 2 is a multiple of 1, 4 is a multiple of 2, 3 is a multiple of 3, and 4 is a multiple of 1.

Example 2

Input: n = 1

Output: 1

Explanation: The only arrangement is [1], and 1 is a multiple of its position, 1.

Example 3

Input: n = 15

Output: 24679

Check your understanding

Work out the answer for this input before you write any code.

n = 5

Constraints

  • 1 ≤ n ≤ 15

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.