Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I stumbled across this interview question:

Given a list of elements in lexicographical order (i.e. ['a', 'b', 'c', 'd']), find the nth permutation

I tried it myself, and it took me about ~30 minutes to solve. (I ended up with a ~8-9 line solution in Python). Just curious -- how long "should" it take to solve this type of problem? Am I taking too long?

like image 225
jasonbogd Avatar asked Oct 27 '25 08:10

jasonbogd


1 Answers

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
        res.append(li[d])
        del(li[d])
    return res

#now that's fast...
nthperm(range(40), 123456789012345678901234567890)
like image 129
Karoly Horvath Avatar answered Oct 29 '25 21:10

Karoly Horvath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!