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: Adjacent Elements Must DivideInput Array236Valid Permutations3626%3=0✓ and 6%2=0✓2636%2=0✓ and 6%3=0✓Answer: 2 Special Permutations
Understanding the Visualization
1
Input
Array [2, 3, 6] with distinct positive integers
2
Check
Adjacent elements must divide: a%b=0 or b%a=0
3
Count
Total valid permutations: 2
Key Takeaway
🎯 Key Insight: Use bitmask DP to efficiently track which elements are used while building valid permutations
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