In coding, a permutation refers to an arrangement of elements in a specific order. It’s a way to rearrange or resequence elements without changing them. For example, given the list [1, 2, 3], permutations could include [1, 2, 3], [2, 1, 3], [3, 2, 1], and so on.
Permutations—LeetCode
Key takeaways:
Permutation is an arrangement of a set’s elements in a specific order. It’s reordering the elements in a set to create different sequences.
Permutations are a fundamental concept in mathematics with applications in various fields due to their ability to model and analyze problems involving order and arrangement. They are essential for counting and probability, discrete mathematics and algorithms, and cryptography.
The time complexity of generating all permutations is O(n!), and the space complexity is O(n * n!). These complexities arise due to the factorial growth in the number of permutations as the input size increases.
A permutation is an arrangement of a set’s elements in a specific order. For a given set of distinct elements, a permutation involves reorganizing those elements into different sequences where the order of the elements matters. For example, for the set, {1, 2, 3}, the possible permutations are {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, and {3, 2, 1}. Each unique sequence is a permutation of the original set.
Permutations are a fundamental concept in mathematics with applications in various fields due to their ability to model and analyze problems involving order and arrangement. They are essential for tasks such as:
Counting and probability: Calculating the number of ways to arrange objects or elements, and determining probabilities in situations where order matters.
Discrete mathematics and algorithms: Studying graph theory, designing algorithms, and solving combinatorial problems.
Cryptography: Encrypting and decrypting data, designing ciphers, and ensuring data security.
Problem statement
In the LeetCode problem, given an array, nums, of distinct integers, return all possible permutations. The order of the permutations does not matter.
Constraints:
1 <= nums.length <= 6-10 <= nums[i] <= 10All the integers of
numsare unique.
Example 1:
In this example, the array [4,5,6] can be rearranged in six ways.
Input: nums = [4,5,6]
Output: [[4,5,6],[4,6,5],[5,4,6],[5,6,4],[6,4,5],[6,5,4]]
Example 2:
Here, the array [7,8] can be rearranged in two ways.
Input: nums = [7,8]
Output: [[7,8],[8,7]]
Example 3:
There is only one possible permutation for a single-element array [9].
Input: nums = [9]
Output: [[9]]
Knowledge test
Attempt the quiz below to test your concepts on the LeetCode permutation problem:
What is the result of buildTree([1, 2, 3])
[[1,2,3],[1,3,2],[3,1,2],[3,2,1]]
[[1,2,3],[1,3,2],[2,1,3],[2,3,1]]
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Algorithm to find the permutations
We can construct an N-array tree, that accumulates the combinations in an accumulator combos when a leaf node is encountered. As we move down the tree, at each step we choose one item from the list combo and recursively build the tree in a depth-first search (DFS) manner. This will be our algorithm for cracking this problem
Lets dry run the problem for Example 1.
The following permutations are therefore possible (from left to right in the tree):
123
132
213
231
312
321
Code to find the permutations
Let’s write down the code for this solution.
global comboscombos = []def buildTree(available:set, combo:list):if len(available)==0:combos.append(combo.copy())else:for chosen in available:residual = available - set([chosen])combo.append(chosen)buildTree(residual, combo)combo.pop(-1)nums = [1, 2, 3]buildTree(set(nums), [])print("The following permutations are possible:\n", combos)
Code explanation
Lines 1–2: We create and initialize the global variable,
combos, that will accumulate the permutations in a list.Lines 4–12: We write the recursive code for gathering the permutations of any given list.
Lines 5–6: This is the termination criteria for recursion. When all the items have be used, the code will append the combination
comboto thecombosaccumulator.Lines 7–12: While the termination criteria has not been met, we use a
for loopto loop over theavailableitems, and at each step, we remove the chosen item from theavailableitems, append the chosen item to the current combinationcombo, and recursively run the function with theresidualitems.
Line 14: We declare the
numslist that contains the items that we want a permutation for.Line 15: We run the code for finding permutations of the
numsarray.Line 16: We print the available permutations.
Time complexity
The function buildTree generates all permutations of the input list nums. To understand the time complexity, consider the following points:
- Total permutations: For a list of length
n, there aren!(or n-factorial) possible permutations. - Recursive calls: The function makes recursive calls; each call iterates over the elements in the available set. In the worst case, this means iterating over
nelements at the first level,n-1elements at the second level, and so on, down to 1 element.
Each recursion level involves iterating through a set of decreasing size, leading to a total number of operations proportional to n * (n-1) * (n-2) * ... * 1 = n!.
Thus, the time complexity of generating all permutations is O(n!).
Space complexity
The space complexity involves the call stack and the space required to store the permutations.
- Call stack: The maximum depth of the recursion is
n, wherenis the length of the input listnums. Each recursion level uses a constant amount of space, so the call stack space complexity isO(n). - Storage for permutations: The
comboslist stores all permutations. As there aren!permutations, and each is a list of lengthn, the space required to store all permutations isO(n * n!).
Combining these, the overall space complexity is dominated by the storage for permutations, which is O(n * n!).
Summary
- Time complexity:
O(n!) - Space complexity:
O(n * n!)
These complexities arise due to the factorial growth in the number of permutations as the input size increases.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What is permutation in coding?
How can you solve permutation problems in coding?
How can you compute a permutation?
Free Resources