Number of times the given string occurs in the array in the range [ l , r ] | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int NumOccurrences ( string arr [ ] , int n , string str , int L , int R ) { unordered_map < string , vector < int > > M ; for ( int i = 0 ; i < n ; i ++ ) { string temp = arr [ i ] ; auto it = M . find ( temp ) ; if ( it == M . end ( ) ) { vector < int > A ; A . push_back ( i + 1 ) ; M . insert ( make_pair ( temp , A ) ) ; } else { it -> second . push_back ( i + 1 ) ; } } auto it = M . find ( str ) ; if ( it == M . end ( ) ) return 0 ; vector < int > A = it -> second ; int y = upper_bound ( A . begin ( ) , A . end ( ) , R ) - A . begin ( ) ; int x = upper_bound ( A . begin ( ) , A . end ( ) , L - 1 ) - A . begin ( ) ; return ( y - x ) ; } int main ( ) { string arr [ ] = { " abc " , " abcabc " , " abc " } ; int n = sizeof ( arr ) / sizeof ( string ) ; int L = 1 ; int R = 3 ; string str = " abc " ; cout << NumOccurrences ( arr , n , str , L , R ) ; return 0 ; }