Check if characters of one string can be swapped to form other | Javascript program to check if characters of one string can be swapped to form other ; if length is not same print no ; Count frequencies of character in first string . ; iterate through the second string decrement counts of characters in second string ; Since lengths are same , some value would definitely become negative if result is false . ; Driver Code
let MAX = 26 ; function targetstring ( str1 , str2 ) { let l1 = str1 . length ; let l2 = str2 . length ; if ( l1 != l2 ) return false ; let map = new Array ( MAX ) ; for ( let i = 0 ; i < map . length ; i ++ ) { map [ i ] = 0 ; } for ( let i = 0 ; i < l1 ; i ++ ) map [ str1 [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; for ( let i = 0 ; i < l2 ; i ++ ) { map [ str2 [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] -- ; if ( map [ str2 [ i ] - ' ' . charCodeAt ( 0 ) ] < 0 ) return false ; } return true ; } let str1 = " " ; let str2 = " " ; if ( targetstring ( str1 , str2 ) ) document . write ( " " ) ; else document . write ( " " ) ;