#60
Permutation Sequence
HardMathRecursionMathBacktracking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a mathematical approach to directly compute the k-th permutation without generating all permutations. It leverages factorials to determine the correct digits in the sequence based on the value of k.
⚙️
Algorithm
4 steps- 1Step 1: Create a list of numbers from 1 to n.
- 2Step 2: Calculate the factorial values for numbers from 1 to n-1.
- 3Step 3: Determine the correct digit for each position by using k and the factorial values to find the index in the list of available numbers.
- 4Step 4: Remove the used number from the list and repeat until the permutation is complete.
solution.py14 lines
1# Full working Python code
2import math
3
4def get_permutation(n, k):
5 nums = list(range(1, n + 1))
6 k -= 1 # Convert to 0-indexed
7 permutation = []
8 factorial = [math.factorial(i) for i in range(n)]
9 for i in range(n):
10 index = k // factorial[n - 1 - i]
11 permutation.append(str(nums[index]))
12 nums.pop(index)
13 k %= factorial[n - 1 - i]
14 return ''.join(permutation)ℹ
Complexity note: The time complexity is O(n) since we perform a constant amount of work for each of the n digits. The space complexity is O(n) for storing the list of numbers and the resulting permutation.
- 1Understanding factorial growth helps in optimizing the solution.
- 2Directly calculating the k-th permutation avoids unnecessary computations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.