Number of times the given string occurs in the array in the range [ l , r ] | Python implementation of the approach ; Function to return the number of occurrences of ; To store the indices of strings in the array ; If current string doesn 't  have an entry in the map  then create the entry ; If the given string is not present in the array ; If the given string is present in the array ; Driver Code
from bisect import bisect_right as upper_bound NEW_LINE from collections import defaultdict NEW_LINE def numOccurences ( arr : list , n : int , string : str , L : int , R : int ) -> int : NEW_LINE INDENT M = defaultdict ( lambda : list ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE if temp not in M : NEW_LINE INDENT A = [ ] NEW_LINE A . append ( i + 1 ) NEW_LINE M [ temp ] = A NEW_LINE DEDENT else : NEW_LINE INDENT M [ temp ] . append ( i + 1 ) NEW_LINE DEDENT DEDENT if string not in M : NEW_LINE INDENT return 0 NEW_LINE DEDENT A = M [ string ] NEW_LINE y = upper_bound ( A , R ) NEW_LINE x = upper_bound ( A , L - 1 ) NEW_LINE return ( y - x ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " abc " , " abcabc " , " abc " ] NEW_LINE n = len ( arr ) NEW_LINE L = 1 NEW_LINE R = 3 NEW_LINE string = " abc " NEW_LINE print ( numOccurences ( arr , n , string , L , R ) ) NEW_LINE DEDENT