First let us start from left. You have N A's and N B's.
First compute the number of strings possible with A as their first character. It is
(2n-1)!/((n-1)!(n)!)
If this value is greater than K, then our string will start with K otherwise it will start with B. Now, to move on we have two cases
Case1: If it starts with A, then the number of A's to check in next step will decrease by 1. And we will check for (2n-2)!/((n-2)!(n!))
Value of K
need not be updated.
Case2: If it starts with B, then the number of B's to check in next step will decrease by 1. And we will check for (2n-2)!/((n-1)!(n-1)!)
Value of 1
will be updated to K - (2n-1)!/((n-1)!(n)!)
and we proceed with new values.
Complexity issues: We need not compute the factorials every time newly. Since we see that the factorial in numerator is decreasing consistently we can divide it with (2n - stepNo)
and get next step's numerator. Similarly for either of the denominators.