Special Permutations — LeetCode 2741 Python Solution
- Problem
- #2741
- Pattern
- Bit Manipulation
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [2,3,6]
- Output
- 2
- Explanation
- [3,6,2] and [2,6,3] are the two special permutations of nums.
Python solution
class Solution:
def specialPerm(self, nums: List[int]) -> int:
mod = 10**9 + 7
n = len(nums)
m = 1 << n
f = [[0] * n for _ in range(m)]
for i in range(1, m):
for j, x in enumerate(nums):
if i >> j & 1:
ii = i ^ (1 << j)
if ii == 0:
f[i][j] = 1
continue
for k, y in enumerate(nums):
if x % y == 0 or y % x == 0:
f[i][j] = (f[i][j] + f[ii][k]) % mod
return sum(f[-1]) % modComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2 \times 2^n) |
| Space | O(n \times 2^n) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2741. Special Permutations is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2741. Special Permutations?
- LeetCode 2741. Special Permutations is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2741. Special Permutations?
- The Python solution on this page runs in O(n^2 \times 2^n).
- What is the space complexity of LeetCode 2741. Special Permutations?
- The Python solution on this page uses O(n \times 2^n) auxiliary space.
- What topics does LeetCode 2741. Special Permutations cover?
- LeetCode 2741. Special Permutations is tagged Bit Manipulation, Array, Dynamic Programming and Bitmask on LeetCode.