![]() |
VOOZH | about |
Given a string str and a character K, the task is to find the count of all the substrings of str that contain the character K.
Examples:
Input: str = "geeks", K = 'g'
Output: 5
"g", "ge", "gee", "geek" and "geeks" are the valid substrings.
Input: str = "geeksforgeeks", K = 'k'
Output: 56
Naive approach A simple approach will be to find all the substrings having character K of the given string and return the count;
Efficient approach: For every index i in the string, find the first index j such that i ? j and str[j] = K. Now, the substrings str[i...j], str[i...j + 1], str[i...j + 2], ..., str[i...n - 1] will all contain the character K at least once. The approach seems to be O(n2) at first but the index j will not be calculated again for every index i, j will be a valid index for all the values of i less than j.
Below is the implementation of the above approach:
56