Special Permutations - Problem

You are given a 0-indexed integer array nums containing n distinct positive integers. A permutation of nums is called special if:

For all indexes 0 <= i < n - 1, either nums[i] % nums[i+1] == 0 or nums[i+1] % nums[i] == 0.

Return the total number of special permutations. As the answer could be large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,6]
Output: 2
💡 Note: Valid special permutations are [3,6,2] and [2,6,3]. In [3,6,2]: 6%3=0 ✓ and 6%2=0 ✓. In [2,6,3]: 6%2=0 ✓ and 6%3=0 ✓.
Example 2 — Single Element
$ Input: nums = [1]
Output: 1
💡 Note: Only one permutation [1] exists, which is trivially special since there are no adjacent pairs to check.
Example 3 — No Valid Permutations
$ Input: nums = [2,3,5]
Output: 0
💡 Note: No permutation is special because none of these numbers divide each other: 2%3≠0, 3%2≠0, 2%5≠0, 5%2≠0, 3%5≠0, 5%3≠0.

Constraints

  • 1 ≤ nums.length ≤ 14
  • 1 ≤ nums[i] ≤ 109
  • All elements in nums are distinct

Visualization

Tap to expand
Special Permutations - DP with Bitmask INPUT Array: nums 2 i=0 3 i=1 6 i=2 Divisibility Graph: 2 3 6 6%2=0 6%3=0 2 and 3: No divisibility n = 3 elements ALGORITHM STEPS 1 Define State dp[mask][last] = count mask: used elements 2 Check Transitions a%b==0 or b%a==0 3 Build Permutations Iterate all 2^n masks 4 Sum Final States mask = 111 (all used) Valid Paths Found: 2 --> 6 --> 3 OK 3 --> 6 --> 2 OK 2 --> 3: Invalid (no div) FINAL RESULT Special Permutations: 2 Valid Permutations: Permutation 1: [2, 6, 3] Permutation 2: [3, 6, 2] Both satisfy divisibility! Output: 2 Key Insight: Use bitmask DP where each bit represents whether an element is used. Track the last element added to ensure valid transitions. Time: O(n^2 * 2^n), Space: O(n * 2^n). Only n elements means 2^n states. Adjacent elements must satisfy: nums[i] % nums[i+1] == 0 OR nums[i+1] % nums[i] == 0. TutorialsPoint - Special Permutations | Dynamic Programming with Bitmask
Asked in
Google 15 Microsoft 12 Amazon 8
18.2K Views
Medium Frequency
~25 min Avg. Time
485 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