Number of Self-Divisible Permutations - Problem

Given an integer n, return the number of self-divisible permutations of the 1-indexed array nums = [1, 2, 3, ..., n].

A 1-indexed array a of length n is self-divisible if for every 1 <= i <= n, gcd(a[i], i) == 1 (where gcd is the greatest common divisor).

A permutation of an array is a rearrangement of its elements. For example, the permutations of [1, 2, 3] are: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1].

Input & Output

Example 1 — Small Case
$ Input: n = 2
Output: 1
💡 Note: Array is [1,2]. For [1,2]: gcd(1,1)=1 ✓, gcd(2,2)=2 ✗. For [2,1]: gcd(2,1)=1 ✓, gcd(1,2)=1 ✓. Only 1 valid arrangement.
Example 2 — Larger Case
$ Input: n = 3
Output: 3
💡 Note: Need gcd(a[i], i) = 1 for all i. Valid arrangements: [1,3,2], [2,3,1], and [3,1,2]. All other permutations fail the GCD constraint.
Example 3 — Edge Case
$ Input: n = 1
Output: 1
💡 Note: Array is [1]. Only arrangement [1]: gcd(1,1)=1 ✓. One valid permutation.

Constraints

  • 1 ≤ n ≤ 15

Visualization

Tap to expand
Self-Divisible Permutations INPUT n = 2 Array nums = [1, 2] 1 2 i=1 i=2 Possible Permutations: [1, 2] [2, 1] Condition: gcd(a[i], i) == 1 for all i from 1 to n ALGORITHM STEPS 1 Check [1, 2] gcd(1,1)=1, gcd(2,2)=2 gcd(2, 2) = 2 != 1 FAIL - Not self-divisible 2 Check [2, 1] gcd(2,1)=1, gcd(1,2)=1 gcd(2,1)=1 OK, gcd(1,2)=1 OK PASS - Self-divisible! 3 Count Valid Sum up passing perms 4 Return Count Only 1 valid permutation Optimal: Bitmask DP tracks used nums FINAL RESULT Valid Permutation Found: [2, 1] Verification: i=1: gcd(2, 1) = 1 i=2: gcd(1, 2) = 1 All conditions satisfied! Output: 1 1 self-divisible permutation Key Insight: Use Bitmask DP to efficiently track which numbers are used. State dp[mask] represents count of valid arrangements where mask indicates used numbers. For each position i, try placing number j if gcd(j,i)=1. Time: O(n! * n) naive, O(2^n * n^2) with bitmask DP. Space: O(2^n) for DP states. TutorialsPoint - Number of Self-Divisible Permutations | Optimal Bitmask DP Approach
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~30 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen