• Customer Support: admin@thealgorists.com
  • Feedback: We are listening to your every feedback, and taking action to constantly improve your learning experience. If you have any feedback, please use this form: https://thealgorists.com/Feedback.
  • If you are a student, email to admin@thealgorists.com to get special student discount.

Problem Statement:

Suppose you have n integers labeled 1 through n.
A permutation of those n integers perm (1-indexed) is considered a "Divisible Permutation" if for every i (1 <= i <= n), either of the following is true:
  • perm[i] is divisible by i.
  • i is divisible by perm[i].

Given an integer n, return the number of the "Divisible Permutations" that you can construct.

Example 1:
Input: n = 2
Output: 2
The first beautiful arrangement is [1,2]:
  • - perm[1] = 1 is divisible by i = 1
  • - perm[2] = 2 is divisible by i = 2

The second beautiful arrangement is [2,1]:
  • - perm[1] = 2 is divisible by i = 1
  • - i = 2 is divisible by perm[2] = 1

Example 2:
Input: n = 1
Output: 1


  • NOTE: I highly recommend going through the Backtracking chapters in the order they are given in the Index page to get the most out of it and be able to build a rock-solid understanding.


Please get yourself comfortable with Backtracking Template before solving this problem.

We would be extending the solution for Permutations and add the condition for divisibility to get the solution for this problem, as you would see in the code below. I am not adding any more details here, since the core algorithm is already discussed in Permutations chapter, which is a prerequisite for this chapter.

This is a Premium content. Please subscribe to access the code.
After subscribing please come back and refresh this page.

Don't forget to take in-depth look at the other backtracking problems in the below link, because that is what would make you comfortable with using the backtracking template and master the art of Backtracking:

The above content is written by:

Abhishek Dey

Abhishek Dey

A Visionary Software Engineer With A Mission To Empower Every Person & Every Organization On The Planet To Achieve More

Microsoft | University of Florida

View LinkedIn profile

If you have any feedback, please use this form: https://thealgorists.com/Feedback.

Subscribe to Our Youtube Channel

Follow Us On LinkedIn