Check if given string can be formed by two other strings or their permutations | Javascript implementation of the approach ; Function to sort the given string using counting sort ; Array to store the count of each character ; Insert characters in the string in increasing order ; Function that returns true if str can be generated from any permutation of the two strings selected from the given vector ; Sort the given string ; Select two strings at a time from given vector ; Get the concatenated string ; Sort the resultant string ; If the resultant string is equal to the given string str ; No valid pair found ; Driver code
let MAX = 26 ; function countingsort ( s ) { let count = new Array ( MAX ) ; count . fill ( 0 ) ; for ( let i = 0 ; i < s . length ; i ++ ) { count [ s [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] ++ ; } let index = 0 ; for ( let i = 0 ; i < MAX ; i ++ ) { let j = 0 ; while ( j < count [ i ] ) { s [ index ++ ] = String . fromCharCode ( i + ' ' . charCodeAt ( ) ) ; j ++ ; } } return s . join ( " " ) ; } function isPossible ( v , str ) { str = countingsort ( str . split ( ' ' ) ) ; for ( let i = 0 ; i < v . length - 1 ; i ++ ) { for ( let j = i + 1 ; j < v . length ; j ++ ) { let temp = v [ i ] + v [ j ] ; temp = countingsort ( temp . split ( ' ' ) ) ; if ( temp == str ) { return true ; } } } return false ; } let str = " " ; let v = [ " " , " " , " " , " " , " " ] ; if ( isPossible ( v , str ) ) document . write ( " " ) ; else document . write ( " " ) ;