Leetcode #2992: Number of Self-Divisible Permutations
In this guide, we solve Leetcode #2992 Number of Self-Divisible Permutations in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given an integer n, return the number of permutations of the 1-indexed array nums = [1, 2, ..., n], such that it's self-divisible. A 1-indexed array a of length n is self-divisible if for every 1 <= i <= n, gcd(a[i], i) == 1.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Bit Manipulation, Array, Math, Dynamic Programming, Backtracking, Bitmask, Number Theory
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: n = 1
Output: 1
Explanation: The array [1] has only 1 permutation which is self-divisible.
Python Solution
class Solution:
def selfDivisiblePermutationCount(self, n: int) -> int:
def dfs(mask: int) -> int:
i = mask.bit_count() + 1
if i > n:
return 1
ans = 0
for j in range(1, n + 1):
if (mask >> j & 1) == 0 and gcd(i, j) == 1:
ans += dfs(mask | 1 << j)
return ans
return dfs(0)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.