Special Permutations — LeetCode 2741 Python Solution

MediumBit ManipulationArrayDynamic ProgrammingBitmask
Problem
#2741
Reading time
3 min

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

Python
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]) % mod

Complexity

MeasureComplexity
TimeO(n^2 \times 2^n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview