Skip to content

Commit d0f1f93

Browse files
KirilBangachevstokhos
authored andcommitted
Add Kth lexicographic permutation (TheAlgorithms#1179)
* Add Kth lexicographic permutation Function that computes the kth lexicographic permtation of 0,1,2,...,n-1 in O(n^2) time * Update kth_lexicographic_permutation.py Addressed requested changes
1 parent 709fda0 commit d0f1f93

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
def kthPermutation(k, n):
2+
"""
3+
Finds k'th lexicographic permutation (in increasing order) of
4+
0,1,2,...n-1 in O(n^2) time.
5+
6+
Examples:
7+
First permutation is always 0,1,2,...n
8+
>>> kthPermutation(0,5)
9+
[0, 1, 2, 3, 4]
10+
11+
The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3],
12+
[0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3],
13+
[1,2,3,0], [1,3,0,2]
14+
>>> kthPermutation(10,4)
15+
[1, 3, 0, 2]
16+
"""
17+
# Factorails from 1! to (n-1)!
18+
factorials = [1]
19+
for i in range(2, n):
20+
factorials.append(factorials[-1] * i)
21+
assert 0 <= k < factorials[-1] * n, "k out of bounds"
22+
23+
permutation = []
24+
elements = list(range(n))
25+
26+
# Find permutation
27+
while factorials:
28+
factorial = factorials.pop()
29+
number, k = divmod(k, factorial)
30+
permutation.append(elements[number])
31+
elements.remove(elements[number])
32+
permutation.append(elements[0])
33+
34+
return permutation
35+
36+
37+
if __name__ == "__main__":
38+
import doctest
39+
40+
doctest.testmod()

0 commit comments

Comments
 (0)