Check if two strings can be made equal by swapping one character among each other | Function that returns true if the string can be made equal after one swap ; A and B are new a and b after we omit the same elements ; Take only the characters which are different in both the strings for every pair of indices ; If the current characters differ ; The strings were already equal ; If the lengths of the strings are two ; If swapping these characters can make the strings equal ; Driver code
function canBeEqual ( a , b , n ) { let A = [ ] ; let B = [ ] ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] != b [ i ] ) { A . push ( a [ i ] ) ; B . push ( b [ i ] ) ; } } if ( A . length == B . length && B . length == 0 ) return true ; if ( A . length == B . length && B . length == 2 ) { if ( A [ 0 ] == A [ 1 ] && B [ 0 ] == B [ 1 ] ) return true ; } return false ; } let A = " " . split ( " " ) ; let B = " " . split ( " " ) ; if ( canBeEqual ( A , B , A . length ) ) document . write ( " " ) ; else document . write ( " " ) ;