I am trying to find the most efficient algorithm to find the index of given permutation of a multiset permutations of '0' and '1'.
Ex: Given {0, 0, 1, 1}. All possible permutations in ascending order are: {0011, 0101, 0110, 1001, 1010, 1100}. These elements are indexed as 0 -> 6. Given s = 0110, the result is 2.
This question is quite similar to here, but his question is on proper set (e.g., {1, 2, 3}). Another similar question is here, but the answer is O(N!). The following code is my try, but it is not efficient too (O(N!)).
def find_index(s, pos): # s is the given permutation, pos is the index list of '1' in s
d_index = 0
c = 0
for i in range (len(pos)-1, -1, -1):
d_index = d_index + 1
if (len-1-pos[i] >= d_index):
c_i = c_i + Combination (d_index, len-1-pos[i])
if (c == 0):
return 0
return c