60. Permutation Sequence
Explanation
To find the kth permutation sequence of numbers from 1 to n, we can follow these steps:
- Generate all permutations of numbers from 1 to n.
- Sort the permutations in lexicographical order.
- Return the kth permutation.
The time complexity of this approach is O(n!) as we are generating all permutations, and the space complexity is also O(n!) to store all permutations.
class Solution {
public String getPermutation(int n, int k) {
List<Integer> numbers = new ArrayList<>();
int[] factorial = new int[n + 1];
factorial[0] = 1;
for (int i = 1; i <= n; i++) {
numbers.add(i);
factorial[i] = factorial[i - 1] * i;
}
k--;
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
int index = k / factorial[n - i];
sb.append(numbers.get(index));
numbers.remove(index);
k -= index * factorial[n - i];
}
return sb.toString();
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.