text: Minimum number of adjacent swaps required to convert a permutation to another permutation by given condition | Function to find the minimum number of swaps ; New array to convert to 1 - based indexing ; Keeps count of swaps ; Check if it is an ' X ' position ; Corner Case ; Swap ; Print the minimum swaps ; Given number N ; Given permutation of N numbers ; Function call
code: def solve ( P , n ) : NEW_LINE INDENT arr = [ ] NEW_LINE arr . append ( 0 ) NEW_LINE for x in P : NEW_LINE INDENT arr . append ( x ) NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == i ) : NEW_LINE INDENT arr [ i ] , arr [ i + 1 ] = arr [ i + 1 ] , arr [ i ] NEW_LINE cnt += 1 NEW_LINE DEDENT DEDENT if ( arr [ n ] == n ) : NEW_LINE INDENT arr [ n - 1 ] , arr [ n ] = arr [ n ] , arr [ n - 1 ] NEW_LINE cnt += 1 NEW_LINE DEDENT print ( cnt ) NEW_LINE DEDENT N = 9 NEW_LINE P = [ 1 , 2 , 4 , 9 , 5 , 8 , 7 , 3 , 6 ] NEW_LINE solve ( P , N ) NEW_LINE