def permutation_rank(p):
    """Given a permutation of {0,..,n-1} find its rank according to lexicographical order

       :param p: list of length n containing all integers from 0 to n-1
       :returns: rank between 0 and n! -1
       :beware: computation with big numbers
       :complexity: `O(n^2)`
    """
    n = len(p)
    fact = 1
    for i in range(2, n):
        fact *= i
    r = 0
    digits = list(range(n))
    for i in range(n - 1):
        q = digits.index(p[i])
        r += fact * q
        del digits[q]
        fact //= n - 1 - i
    return r
