Find an anagram of given String having different characters at corresponding indices | Function to find anagram of string such that characters at the same indices are different ; Copying our original string for comparison ; Declaring the two pointers ; Checking the given condition ; When string length is odd ; The mid element ; If the characters are the same , then perform the swap operation as illustrated ; Check if the corresponding indices has the same character or not ; If string follows required condition ; Driver Code
function swap ( str , i , j ) { if ( i == j ) { return str ; } if ( j < i ) { var temp = j ; j = i ; i = temp ; } if ( i >= str . length ) { return str ; } return str . substring ( 0 , i ) + str [ j ] + str . substring ( i + 1 , j ) + str [ i ] + str . substring ( j + 1 ) ; } function findAnagram ( s ) { let check = s . slice ( ) ; let i = 0 , j = s . length - 1 ; while ( i < s . length && j >= 0 ) { if ( s [ i ] != s [ j ] && check [ i ] != s [ j ] && check [ j ] != s [ i ] ) { s = swap ( s , i , j ) i ++ ; j = s . length - 1 ; } else { j -- ; } } if ( s . length % 2 != 0 ) { let mid = s . length / 2 ; if ( check [ mid ] == s [ mid ] ) { for ( let i = 0 ; i < s . length ; i ++ ) { if ( check [ i ] != s [ mid ] && s [ i ] != s [ mid ] ) { s = swap ( s , i , mid ) break ; } } } } let ok = true ; for ( let i = 0 ; i < s . length ; i ++ ) { if ( check [ i ] == s [ i ] ) { ok = false ; break ; } } if ( ok ) document . write ( s ) ; else document . write ( - 1 ) ; } let S = " " ; findAnagram ( S ) ;