Sponsored
Sponsored
This approach leverages the factorial number system, where the number of permutations starting with a particular digit can be determined by the factorial of (n-1). We adjust k for zero-based indexing and deduct permutations as we determine each digit sequentially.
Time Complexity: O(n^2) due to potential shifts in the numbers array.
Space Complexity: O(n) for storing factorials and numbers.
1def getPermutation(n: int, k: int) -> str:
2 import math
3 numbers = list(range(1, n+1))
4 k -= 1
5 result = []
6
7 for i in range(n, 0, -1):
8 idx = k // math.factorial(i-1)
9 result.append(numbers.pop(idx))
10 k %= math.factorial(i-1)
11 return ''.join(map(str, result))
12
13n = 3
14k = 3
15print(getPermutation(n, k))
This Python implementation utilizes math.factorial to handle factorial calculations. It efficiently builds the permutation using list manipulation to determine which element should appear in each position.
This approach generates permutations using a traditional backtracking method, with the goal of finding the k-th permutation without necessarily generating all permutations explicitly.
Time Complexity: O(n!) for generating permutations.
Space Complexity: O(n) due to recursion and string storage.
1#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
string getPermutation(int n, int k) {
string numbers;
for (int i = 1; i <= n; i++)
numbers += to_string(i);
string result;
do {
k--;
if (k == 0) {
result = numbers;
break;
}
} while (next_permutation(numbers.begin(), numbers.end()));
return result;
}
int main() {
int n = 3, k = 3;
cout << getPermutation(n, k) << endl;
return 0;
}
This C++ solution uses the standard library's next_permutation
to iterate through permutations until the k-th is found, optimizing the traditional backtracking method.