Given a list of elements in lexicographical order (i.e. [‘a’, ‘b’, ‘c’, ‘d’]), find the nth permutation – Average time to solve?

9 min, including test

import math

def nthperm(li, n):
    n -= 1
    s = len(li)
    res = []
    if math.factorial(s) <= n:
        return None
    for x in range(s-1,-1,-1):
        f = math.factorial(x)
        d = n / f
        n -= d * f
    return res

#now that's fast...
nthperm(range(40), 123456789012345678901234567890)

Leave a Comment