This solution occurred to me (but I have not tested it yet).
The first digit is in the range from 1 to N, so you can get from the first digit whether your permutation is in what size block (N-1)!
2*(2!) + X where X = 0..2!-1
Then you can recursively apply this to the following digits (which is one of the (N-1)! Permutations).
So, with arbitrary N you can do the following algorithm:
X = 0 while string <> "" X += ((first digit) - 1) * (N-1)! decrease all digits in string by 1 which are > first digit remove first digit from string N -= 1 return X
In your case:
X = 2 s = "213" X += (2-1) * 2! => 2 s = "12" X += (1-1) * 1! => 2 s = "1" X += (1-1) * 0! => 2
Thus, this algorithm is O (N ^ 2).
source share