Substrings starting with vowel and ending with consonants and vice versa | Returns true if ch is vowel ; Function to check consonant ; in case of empty string , we can 't fullfill the  required condition, hence we return ans as 0. ; co [ i ] is going to store counts of consonants from str [ len - 1 ] to str [ i ] . vo [ i ] is going to store counts of vowels from str [ len - 1 ] to str [ i ] . ; Counting consonants and vowels from end of string . ; Now we traverse string from beginning ; If vowel , then count of substrings starting with str [ i ] is equal to count of consonants after it . ; If consonant , then count of substrings starting with str [ i ] is equal to count of vowels after it . ; Driver code
function isVowel ( ch ) { return ( ch === " " ch === " " ch === " " ch === " " ch === " " ) ; } function isCons ( ch ) { return ( ch !== " " && ch !== " " && ch !== " " && ch !== " " && ch !== " " ) ; } function countSpecial ( str ) { var len = str . length ; if ( len == 0 ) return 0 ; var co = new Array ( len + 1 ) . fill ( 0 ) ; var vo = new Array ( len + 1 ) . fill ( 0 ) ; if ( isCons ( str [ len - 1 ] ) === true ) co [ len - 1 ] = 1 ; else vo [ len - 1 ] = 1 ; for ( var i = len - 2 ; i >= 0 ; i -- ) { if ( isCons ( str [ i ] ) === true ) { co [ i ] = co [ i + 1 ] + 1 ; vo [ i ] = vo [ i + 1 ] ; } else { co [ i ] = co [ i + 1 ] ; vo [ i ] = vo [ i + 1 ] + 1 ; } } var ans = 0 ; for ( var i = 0 ; i < len ; i ++ ) { if ( isVowel ( str [ i ] ) ) ans = ans + co [ i + 1 ] ; else ans = ans + vo [ i + 1 ] ; } return parseInt ( ans ) ; } var str = " " ; document . write ( countSpecial ( str . split ( " " ) ) ) ;