Number of Times the given String Occurs in the Array in the Range [l, r]


Introduction

In this tutorial, we implement examples using C++ to find the number of times an input string occurs in an array of the range [l,r]. Only lowercase alphabets are used in the string array to resolve this task. Different strings are stored in the string array and traversed to check if a particular string exists. This is for a given range of L and R. L and R are the starting and ending index values of an array to search a string for that range in the input string array. Find string lying between L and R of the input array.

Demonstration 1

str_arr[] = {“abc”, “def”, “ghi”} 
str = “abc”
L = 1, R = 2

Output

0

In the above demonstration, the values of L and R are 1 and 2 respectively. We check if the string “abc” is present in str_arr within the range of str_arr[1, 2]. Iterate the str_array[] from the starting index value of 1 and search for string “abc” till the index value is 2. We find that “abc” does not exist between [1, 2] as it exists at the index value 0. Hence, the output is 0.

Demonstration 2

str_arr = {“abc”, “ghi”, “cde”} 
str = “cde”
L = 1, R = 3

Output

1

In the above demonstration, we check if the string “cde” is present in the str_arr within the range of str_arr[1, 3]. Iterate the str_arr to check all its elements for the given range. “cde” exists in the str_arr[1, 2]. Hence, the output is 1.

C++ Library Functions Used in the Examples

Syntax

size of() : it is a keyword in C++ which determines the size of an operator, data type, and variables. It estimates the size at compile time.

sizeof(data type);

unordered_map() : It is a container class in the C++ standard library and is defined in the header file. It stores its elements unordered and in key-value pairs. Each key in a key-value pair is unique with its associated value.

unordered_map<data_type> nameofunordered_map;

unordered_map: find() : It is a member function of the unordered_map class. It searches for a particular key in unordered_map key-value pairs.

unordered_map.find(key); 

unordered_map:end() : It is a member function of the unordered_map class and is defined in the <std> header file. It returns the iterator pointing to the position beyond the last element of the unordered_map.

unordered_map.end(value);

vector() : It is a size unbounded array in C++ that provides contiguous memory location to its elements. It is defined in the <std> header file.

vector <data_type>vector_name;

upper_bound() : It refers to the position or iterator of the next position of the stored elements which is greater than the specified value.

upper_bound(value);

begin() : it returns the first position of the elements stored in a vector array. It is a predefined function in the C++ library. This function does not take any parameters.

vector_name.begin(); 

Make_pair() : It is defined in the standard C++ Template Library. It is used to make pair values using its first and second parameters. Parameter values can be of different data types.

make_pair(value1, value2);

Algorithm

  • Initialize a string array to store different string values.

  • Define a string str to be checked in the string array.

  • Define the values of the L and R.

  • Iterate over each element of the string array to compare str.

  • Take a counter variable and initialize it with 0.

  • If str matches the elements of an array, increase its value.

  • Return the counter variable and print it.

Example 1

We implement one of the demonstrations using C++ programming concepts and its library functions. We use a simple approach, defining a string array “str_arr{}”. Compare each element of the str_arr{} for the given range for the input string str. Use a counter variable to count the occurrence of input string for a given range in the str_arr{}.

#include <bits/stdc++.h>
using namespace std;
 
// User-defined function to count the number of occurrence of a given string
int totalAppearence(string str_arr[], int a, string s, int L, int R){
      //counter variable
      int cnt=0;
   
      //Iterating for the given values of L and R
    for (int x = L-1; x < R; x++){
          //condition for matches string
          if(str_arr[x]==s)cnt++;
    }
 
    return cnt;
}
 
// Program Controller
int main(){
    string str_arr[] = { "abc", "def", "abc" };
    int a = sizeof(str_arr) / sizeof(string);
    int L = 1;
    int R = 2;
    string s = "abc";
 
    cout << "Number of times input string appear in the array is:" << totalAppearence(str_arr, a, s, L, R);
    return 0;
}

Output

Number of times input string appear in the array is: 1

Example 2

To implement one of the above demonstrations, we used unordered_map to store the string array values. The unordered_map indices are used to compare the input string within the defined range with the array elements.

Unordered_map helps search fast due to its mapped values and key values pair.

#include <bits/stdc++.h>
using namespace std;
 
// User-defined function to count the occurrence of input string
int totalAppearence(string str_arr[], int a, string s, int L, int R)
{
    // initialized unordered_map
    unordered_map<string, vector<int> > N;
    for (int x = 0; x < a; x++) 
    {
        string t = str_arr[x];
        auto i = N.find(t);
 
        if (i == N.end()) 
        {
            vector<int> B;
            B.push_back(x + 1);
            N.insert(make_pair(t, B));
        }
        else 
        {
            i->second.push_back(x + 1);
        }
    }
 
    auto i = N.find(s);
 
    // When string is not in array
    if (i == N.end())
        return 0;
 
    //when string is found in array
    vector<int> B = i->second;
    int m = upper_bound(B.begin(), B.end(), R) - B.begin();
    int n = upper_bound(B.begin(), B.end(), L - 1) - B.begin();
 
    return (m - n);
}
 
// program controller
int main()
{
    string str_arr[] = { "abc", "dfe", "cba" };
    int a = sizeof(str_arr) / sizeof(string);
    int L = 1;
    int R = 1;
    string s = "gef";
 
    cout << "Number of times input string appears in the array is : " << totalAppearence(str_arr, a, s, L, R);
 
    return 0;
}

Output

Number of times input string appears in the array is : 0

Conclusion

We reached the end of this tutorial to find the number of times an input string occurs in a string array of Range L, and R. Demonstrated the task to make the problem statement clear for easy implementation. We implemented two examples using different C++ library functions. In the first example, we take a string array and iterate over the defined range element and check if it matches the input string or not. In the second approach, use an unordered_map to store indices. To search for the occurrence of the input string, search the unordered_map indices and print the result.

Updated on: 18-Aug-2023

53 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements