Skip to content

Add Kth lexicographic permutation #1179

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 13, 2019
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions maths/kth_lexicographic_permutation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
def kthPermutation(k, n):
"""
Finds k'th lexicographic permutation (in increasing order) of
0,1,2,...n-1 in O(n^2) time.

Examples:
First permutation is always 0,1,2,...n
>>> kthPermutation(0,5)
[0, 1, 2, 3, 4]

The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3],
[0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3],
[1,2,3,0], [1,3,0,2]
>>> kthPermutation(10,4)
[1, 3, 0, 2]
"""
# Factorails from 1! to (n-1)!
factorials = [1]
for i in range(2, n):
factorials.append(factorials[-1] * i)
assert (
0 <= k and k < factorials[-1] * n
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

k is only needed once.
assert 0 <= k < factorials[-1] * n, "k out of bounds"

), "k out of bounds"

permutation = []
elements = list(range(n))

# Find permutation
while factorials:
factorial = factorials.pop()
number = k // factorial
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

number, k = divmod(factorial) # and delete line 34

permutation.append(elements[number])
elements.remove(elements[number])
k = k % factorial
permutation.append(elements[0])

return permutation


if __name__ == "__main__":
import doctest

doctest.testmod()