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.
1
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 <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5void swap(char *a, char *b) {
6 char temp = *a;
7 *a = *b;
8 *b = temp;
9}
10
11int count = 0;
12char *perm = NULL;
13
14void permute(char *str, int start, int end, int k) {
15 if (start == end) {
16 count++;
17 if (count == k) {
18 strcpy(perm, str);
19 }
20 } else {
21 for (int i = start; i <= end; i++) {
22 swap((str + start), (str + i));
23 permute(str, start + 1, end, k);
24 swap((str + start), (str + i));
25 }
26 }
27}
28
29char *getPermutation(int n, int k) {
30 char *numbers = malloc((n + 1) * sizeof(char));
31 for (int i = 0; i < n; i++)
32 numbers[i] = '1' + i;
33 numbers[n] = '\0';
34 perm = malloc((n + 1) * sizeof(char));
35 permute(numbers, 0, n - 1, k);
36 free(numbers);
37 return perm;
38}
39
40int main() {
41 int n = 3, k = 3;
42 char *result = getPermutation(n, k);
43 printf("%s\n", result);
44 free(result);
45 return 0;
46}
This C solution uses a recursive backtracking approach to generate permutations, counting them until reaching the desired k-th permutation, which is stored for output.
Solve with full IDE support and test cases