Leetcode 2741: Special Permutations

grid47
grid47
Exploring patterns and algorithms
Feb 6, 2024 8 min read

You are given a list of distinct positive integers nums. A permutation of nums is considered special if, for every pair of consecutive numbers in the permutation, one number is divisible by the other. Your task is to return the total number of special permutations of nums, modulo 10^9 + 7.
Problem
Approach
Steps
Complexity
Input: The input consists of a single array of distinct positive integers `nums`.
Example: nums = [2, 3, 6]
Constraints:
• 2 <= nums.length <= 14
• 1 <= nums[i] <= 10^9
Output: Return the total number of special permutations modulo `10^9 + 7`.
Example: Output: 2
Constraints:
Goal: To count the number of special permutations of `nums` that satisfy the divisibility condition.
Steps:
• Build a graph representing the divisibility relation between numbers in `nums`.
• Use depth-first search (DFS) to explore all valid permutations while respecting the divisibility constraints.
• Return the count of special permutations modulo `10^9 + 7`.
Goal: The array `nums` has at least two elements, and each element is a positive integer within the given range.
Steps:
• 2 <= nums.length <= 14
• 1 <= nums[i] <= 10^9
Assumptions:
• All elements in `nums` are distinct positive integers.
• The array has at least two elements.
Input: nums = [2, 3, 6]
Explanation: The two special permutations of `nums` are `[3, 6, 2]` and `[2, 6, 3]`.

Input: nums = [5, 10, 2]
Explanation: The four special permutations of `nums` are `[2, 10, 5]`, `[5, 2, 10]`, `[10, 5, 2]`, and `[10, 2, 5]`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus