#2741
Special Permutations
MediumArrayDynamic ProgrammingBit ManipulationBitmaskDynamic ProgrammingBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n * 2^n) |
| Space | O(n) | O(n * 2^n) |
💡
Intuition
Time O(n * 2^n)Space O(n * 2^n)
Using dynamic programming with bit masking allows us to efficiently track which numbers have been used in the permutation and the last number added, significantly reducing the number of checks needed.
⚙️
Algorithm
3 steps- 1Step 1: Create a DP table where dp[mask][last] represents the number of special permutations using the numbers represented by 'mask' with 'last' as the last number in the permutation.
- 2Step 2: Iterate through all possible masks and for each mask, try to add each unused number to the permutation, checking the special condition.
- 3Step 3: Sum all valid permutations from the DP table and return the result modulo 10^9 + 7.
solution.py20 lines
1# Full working Python code
2def special_permutations(nums):
3 n = len(nums)
4 dp = [[0] * n for _ in range(1 << n)]
5 MOD = 10**9 + 7
6
7 for i in range(n):
8 dp[1 << i][i] = 1
9
10 for mask in range(1 << n):
11 for last in range(n):
12 if dp[mask][last] == 0:
13 continue
14 for next in range(n):
15 if mask & (1 << next):
16 continue
17 if nums[last] % nums[next] == 0 or nums[next] % nums[last] == 0:
18 dp[mask | (1 << next)][next] = (dp[mask | (1 << next)][next] + dp[mask][last]) % MOD
19
20 return sum(dp[(1 << n) - 1]) % MODℹ
Complexity note: The time complexity is O(n * 2^n) because we explore all subsets of the numbers (2^n) and for each subset, we check each number (n). The space complexity is O(n * 2^n) for storing the DP table.
- 1Understanding the special condition is crucial for both brute-force and optimal approaches.
- 2Using bit masking allows us to efficiently track used numbers and avoid redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.