text: Minimum number of adjacent swaps for arranging similar elements together | Function to find minimum swaps ; visited array to check if value is seen already ; If the arr [ i ] is seen first time ; stores the number of swaps required to find the correct position of current element 's partner ; Increment count only if the current element has not been visited yet ( if is visited , means it has already been placed at its correct position ) ; If current element 's partner is found ; Driver Code
code: def findMinimumAdjacentSwaps ( arr , N ) : NEW_LINE INDENT visited = [ False ] * ( N + 1 ) NEW_LINE minimumSwaps = 0 NEW_LINE for i in range ( 2 * N ) : NEW_LINE INDENT if ( visited [ arr [ i ] ] == False ) : NEW_LINE INDENT visited [ arr [ i ] ] = True NEW_LINE count = 0 NEW_LINE for j in range ( i + 1 , 2 * N ) : NEW_LINE INDENT if ( visited [ arr [ j ] ] == False ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT elif ( arr [ i ] == arr [ j ] ) : NEW_LINE INDENT minimumSwaps += count NEW_LINE DEDENT DEDENT DEDENT DEDENT return minimumSwaps NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 3 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE N //= 2 NEW_LINE print ( findMinimumAdjacentSwaps ( arr , N ) ) NEW_LINE DEDENT