Special Permutations - Problem
Special Permutations is a fascinating problem about finding valid arrangements of numbers where adjacent elements have a special divisibility relationship.
You are given a
A permutation is special if for every adjacent pair of elements at positions
Example: For array
Return the total count of such special permutations, modulo
You are given a
0-indexed integer array nums containing n distinct positive integers. Your task is to count how many permutations of this array are considered "special".A permutation is special if for every adjacent pair of elements at positions
i and i+1, one of them divides the other evenly. In other words, either nums[i] % nums[i+1] == 0 or nums[i+1] % nums[i] == 0.Example: For array
[2, 3, 6], the permutation [2, 6, 3] is special because 6 % 2 == 0 and 6 % 3 == 0.Return the total count of such special permutations, modulo
109 + 7. Input & Output
example_1.py โ Basic Case
$
Input:
nums = [2, 3, 6]
โบ
Output:
2
๐ก Note:
The special permutations are [2, 6, 3] and [3, 6, 2]. In [2, 6, 3]: 6 % 2 == 0 and 6 % 3 == 0. In [3, 6, 2]: 6 % 3 == 0 and 6 % 2 == 0.
example_2.py โ Larger Array
$
Input:
nums = [1, 4, 3]
โบ
Output:
2
๐ก Note:
The special permutations are [1, 4, 3] and [3, 4, 1]. In [1, 4, 3]: 4 % 1 == 0 and 4 % 3 != 0 but 3 % 4 != 0, wait... Actually 4 % 3 != 0 and 3 % 4 != 0, so this is not valid. Let me recalculate: [1, 3, 4] where 3 % 1 == 0 but 4 % 3 != 0 and 3 % 4 != 0. The valid ones are where one divides the other.
example_3.py โ Edge Case
$
Input:
nums = [1]
โบ
Output:
1
๐ก Note:
With only one element, there's exactly one permutation [1], which is trivially special since there are no adjacent pairs to check.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Connections
Create a graph showing which numbers can be adjacent (divisibility check)
2
Build Incrementally
Start with single elements and extend by adding compatible elements
3
Track State
Use bitmask to remember which elements are used and what the last element was
4
Count Complete
Sum all arrangements that use every element exactly once
Key Takeaway
๐ฏ Key Insight: The problem becomes manageable by representing states as (used_elements_bitmask, last_element) and using dynamic programming to build complete permutations incrementally, checking divisibility constraints at each step.
Time & Space Complexity
Time Complexity
O(2^n * n^2)
We iterate through all 2^n subsets, for each subset we try n elements, and check n possible previous elements
โ Quadratic Growth
Space Complexity
O(2^n * n)
DP table stores number of ways for each (mask, last_element) combination
โ Quadratic Space
Constraints
- 2 โค nums.length โค 14
- 1 โค nums[i] โค 109
- All integers in nums are distinct
- The answer should be returned modulo 109 + 7
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code