Number of ways in which the substring in range [ L , R ] can be formed using characters out of the range | Java implementation of the approach ; Function to return the number of ways to form the sub - string ; Initialize a hash - table with 0 ; Iterate in the string and count the frequency of characters that do not lie in the range L and R ; Out of range characters ; Stores the final number of ways ; Iterate for the sub - string in the range L and R ; If exists then multiply the number of ways and decrement the frequency ; If does not exist the sub - string cannot be formed ; Return the answer ; Driver code
class GfG { static int calculateWays ( String s , int n , int l , int r ) { int freq [ ] = new int [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( i < l i > r ) freq [ s . charAt ( i ) - ' a ' ] ++ ; } int ways = 1 ; for ( int i = l ; i <= r ; i ++ ) { if ( freq [ s . charAt ( i ) - ' a ' ] != 0 ) { ways = ways * freq [ s . charAt ( i ) - ' a ' ] ; freq [ s . charAt ( i ) - ' a ' ] -- ; } else { ways = 0 ; break ; } } return ways ; } public static void main ( String [ ] args ) { String s = " cabcaab " ; int n = s . length ( ) ; int l = 1 , r = 3 ; System . out . println ( calculateWays ( s , n , l , r ) ) ; } }