Sub | Function that returns the index of next occurrence of the character c in string str starting from index start ; Starting from start ; If current character = c ; Not found ; Function to return the count of required sub - strings ; Stores running count of ' x ' starting from the end ; Next index of ' x ' starting from index 0 ; Next index of ' y ' starting from index 0 ; To store the count of required sub - strings ; If ' y ' appears before ' x ' it won 't contribute to a valid sub-string ; Find next occurrence of ' y ' ; If ' y ' appears after ' x ' every sub - string ending at an ' x ' appearing after this ' y ' and starting with the current ' x ' is a valid sub - string ; Find next occurrence of ' x ' ; Return the count ; Driver code
function nextIndex ( str , start , c ) { for ( let i = start ; i < str . length ; i ++ ) { if ( str [ i ] == c ) return i ; } return - 1 ; } function countSubStrings ( str ) { let i , n = str . length ; let countX = new Array ( n ) ; let count = 0 ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == ' ' ) count ++ ; countX [ i ] = count ; } let nextIndexX = nextIndex ( str , 0 , ' ' ) ; let nextIndexY = nextIndex ( str , 0 , ' ' ) ; count = 0 ; while ( nextIndexX != - 1 && nextIndexY != - 1 ) { if ( nextIndexX > nextIndexY ) { nextIndexY = nextIndex ( str , nextIndexY + 1 , ' ' ) ; continue ; } else { count += countX [ nextIndexY ] ; nextIndexX = nextIndex ( str , nextIndexX + 1 , ' ' ) ; } } return count ; } let s = " " ; document . write ( countSubStrings ( s ) ) ;