# Logic for " Ambiguous Permutations "

For the problem [Ambiguous Permutations][1] I read in one of the posted solutions the following piece of code which executes very fast :

``````boolean check=true;
int loc=0;
for(int i=0;i<array.length;i++){
loc=array[i];
if (array[loc-1]!=i+1){
check=false;
break;
}
}
``````

Can someone please explain me how to reach this expression mathematically ? How to derive this ?
I couldn’t figure out how the relation was obtained / the steps for it
[1]: http://www.codechef.com/problems/PERMUT2

That’s not so complicated. You want to chcek, if permutation is equivalent to inverse permutation. When you read statement carefully, you should be able to understand, that when on second (2) position of permutation is number 5, than in inverse permutation on fifth (5) position is number 2.

More generally, if on i-th position is number j, than in inverse permutation on j-th position is number i. Now proceed through permutation. On i-th position is number loc = array[i]. And this permutation should be equal to inverse permutation. So on position loc must be number i (±1 in code is, because he numbered from 0). If this condition isn’t met, than this permutation is not ambiguous.

//