The Number of Self-Divisible Permutations problem asks you to count permutations of numbers 1 to n where for each position i, perm[i] is divisible by i (1-indexed). This coding problem uses bitmask DP to count valid assignments where each position's divisibility constraint is satisfied.
Salesforce asks this to test bitmask DP with divisibility constraints — a variant of the assignment problem. For small n, enumerate all permutations using backtracking with bitmask state. The array, math, number theory, bitmask, backtracking, bit manipulation, and dynamic programming interview pattern is the core.
Bitmask DP. dp[mask] = number of ways to assign values to the first popcount(mask) positions using exactly the values indicated by the set bits in mask. For each position i (= popcount(mask) + 1), try each unused value v (bit not in mask): if v % i == 0, update dp[mask | (1<<(v-1))] += dp[mask]. Answer = dp[(1<<n) - 1].
n=3. Check permutations of [1,2,3] where perm[1]%1==0, perm[2]%2==0, perm[3]%3==0.
value % position == 0.Bitmask DP assignment problems follow the template: dp[mask] = ways to assign elements to the first k positions (k = popcount(mask)) using exactly the elements in mask. Transition: try each unused element as the next assignment, check constraints, update. The key constraint here is divisibility. Practice the Traveling Salesman Problem bitmask DP first, then adapt to assignment constraints like this one.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximize Score After N Operations | Hard | Solve | |
| Beautiful Arrangement | Medium | Solve | |
| Campus Bikes II | Medium | Solve | |
| Count the Number of Square-Free Subsets | Medium | Solve | |
| Fair Distribution of Cookies | Medium | Solve |