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
def calculateWays ( s , n , l , r ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i < l or i > r ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT ways = 1 NEW_LINE for i in range ( l , r + 1 , 1 ) : NEW_LINE INDENT if ( freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] ) : NEW_LINE INDENT ways = ways * freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] NEW_LINE freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT ways = 0 NEW_LINE break NEW_LINE DEDENT DEDENT return ways NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " cabcaab " NEW_LINE n = len ( s ) NEW_LINE l = 1 NEW_LINE r = 3 NEW_LINE print ( calculateWays ( s , n , l , r ) ) NEW_LINE DEDENT