Number of ways in which the substring in range [ L , R ] can be formed using characters out of the range | 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
< ? php function calculateWays ( $ s , $ n , $ l , $ r ) { $ freq = array ( ) ; for ( $ i = 0 ; $ i < 26 ; $ i ++ ) { $ freq [ $ i ] = 0 ; } for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ i < $ l $ i > $ r ) $ freq [ ord ( $ s [ $ i ] ) - 97 ] ++ ; } $ ways = 1 ; for ( $ i = $ l ; $ i <= $ r ; $ i ++ ) { if ( $ freq [ ord ( $ s [ $ i ] ) - 97 ] ) { $ ways = $ ways * $ freq [ ord ( $ s [ $ i ] ) - 97 ] ; $ freq [ ord ( $ s [ $ i ] ) - 97 ] -- ; } else { $ ways = 0 ; break ; } } return $ ways ; } $ s = " cabcaab " ; $ n = strlen ( $ s ) ; $ l = 1 ; $ r = 3 ; echo calculateWays ( $ s , $ n , $ l , $ r ) ; ? >