text: Check if a string can be made equal to another string by swapping or replacement of characters | Function to find if given Strings are same or not ; Base Condition ; Stores frequency of characters of the String str1 and str2 ; Traverse Strings str1 & str2 and store frequencies in a [ ] and b [ ] ; Check if both Strings have same characters or not ; If a character is present in one String and is not in another String , return false ; Sort the array a [ ] and b [ ] ; Check arrays a and b contain the same frequency or not ; If the frequencies are not the same after sorting ; At this point , str1 can be converted to str2 ; Driver Code
code: function sameStrings ( str1 , str2 ) { var N = str1 . length ; var M = str2 . length ; if ( N !== M ) { return false ; } var a = new Array ( 256 ) . fill ( 0 ) ; var b = new Array ( 256 ) . fill ( 0 ) ; for ( var j = 0 ; j < N ; j ++ ) { a [ str1 [ j ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] ++ ; b [ str2 [ j ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] ++ ; } var i = 0 ; while ( i < 256 ) { if ( ( a [ i ] === 0 && b [ i ] === 0 ) || ( a [ i ] !== 0 && b [ i ] !== 0 ) ) { i ++ ; } else { return false ; } } a . sort ( ( x , y ) => x - y ) ; b . sort ( ( x , y ) => x - y ) ; for ( var j = 0 ; j < 256 ; j ++ ) { if ( a [ j ] !== b [ j ] ) return false ; } return true ; } var S1 = " " , S2 = " " ; if ( sameStrings ( S1 , S2 ) ) document . write ( " " + " " ) ; else document . write ( " " + " " ) ;