Lexicographically first alternate vowel and consonant string | JavaScript implementation of lexicographically first alternate vowel and consonant String ; ' ch ' is vowel or not ; create alternate vowel and consonant String str1 [ 0. . . l1 - 1 ] and str2 [ start ... l2 - 1 ] ; first adding character of vowel / consonant then adding character of consonant / vowel ; function to find the required lexicographically first alternate vowel and consonant String ; hash table to store frequencies of each character in ' str ' ; initialize all elements of char_freq [ ] to 0 ; count vowels ; count consonants ; update frequency of ' ch ' in char_freq [ ] ; no such String can be formed ; form the vowel String ' vstr ' and consonant String ' cstr ' which contains characters in lexicographical order ; remove first character of vowel String then create alternate String with cstr [ 0. . . nc - 1 ] and vstr [ 1. . . nv - 1 ] ; remove first character of consonant String then create alternate String with vstr [ 0. . . nv - 1 ] and cstr [ 1. . . nc - 1 ] ; if both vowel and consonant strings are of equal length start creating String with consonant ; start creating String with vowel ; Driver code
let SIZE = 26 ; function isVowel ( ch ) { if ( ch == ' ' ch == ' ' ch == ' ' ch == ' ' ch == ' ' ) { return true ; } return false ; } function createAltStr ( str1 , str2 , start , l ) { let finalStr = " " ; for ( let i = 0 , j = start ; j < l ; i ++ , j ++ ) { finalStr = ( finalStr + str1 [ i ] ) + str2 [ j ] ; } return finalStr ; } function findAltStr ( str ) { let char_freq = new Array ( SIZE ) ; for ( let i = 0 ; i < SIZE ; i ++ ) char_freq [ i ] = 0 ; let nv = 0 , nc = 0 ; let vstr = " " , cstr = " " ; let l = str . length ; for ( let i = 0 ; i < l ; i ++ ) { let ch = str [ i ] ; if ( isVowel ( ch ) ) { nv ++ ; } else { nc ++ ; } char_freq [ ch . charCodeAt ( 0 ) - 97 ] ++ ; } if ( Math . abs ( nv - nc ) >= 2 ) { return " " ; } for ( let i = 0 ; i < SIZE ; i ++ ) { let ch = String . fromCharCode ( i + 97 ) ; for ( let j = 1 ; j <= char_freq [ i ] ; j ++ ) { if ( isVowel ( ch ) ) { vstr += ch ; } else { cstr += ch ; } } } if ( nv > nc ) { return ( vstr [ 0 ] + createAltStr ( cstr , vstr , 1 , nv ) ) ; } if ( nc > nv ) { return ( cstr [ 0 ] + createAltStr ( vstr , cstr , 1 , nc ) ) ; } if ( cstr [ 0 ] < vstr [ 0 ] ) { return createAltStr ( cstr , vstr , 0 , nv ) ; } return createAltStr ( vstr , cstr , 0 , nc ) ; } let str = " " ; document . write ( findAltStr ( str ) ) ;