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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With