Queries to find frequencies of a string within specified substrings
Last Updated :
26 May, 2021
Given a string S and a matrix Q of queries, each specifying the starting and ending indices L( = Q[i][0]) and R( = Q[i][0]) respectively of a substring of S, the task is to find the frequency of string K in substring [L, R].
Note: The ranges follow the 1-based indexing.
Examples:
Input: S = "GFGFFGFG", K = "GFG", Q = {{1, 8}, {3, 5}, {5, 8}}
Output:
2
0
1
Explanation: For query 1, there are 2 ("GFG") substrings from index 1 to index 8. One is from index 1 to 3 and the other is from index 6 to 8.
For query 2, there are 0 ("GFG") substrings from index 3 to 5.
For query 3, there are 1 ("GFG") substrings from index 5 to index 8. The one and only substring are from index 6 to 8.
Input: S = "ABCABCABABC", K = "ABC", Q = {{1, 6}, {5, 11}}
Output:
2
1
Naive Approach:
Run a loop from L to R for all the queries. Count occurrence of the string K and return count.
Time Complexity: O(length of Q * |S|).
Efficient Approach:
Pre-compute and store the frequency of K for every index. Now, for computing the frequency of the string in a range [L, R], we just need to calculate the difference between the frequency of K at index (R-1) and (L-1).
Below is the implementation of the above approach:
C++
// C++ Program to find
// frequency of a string K
// in a substring [L, R] in S
#include <bits/stdc++.h>
#define max_len 100005
using namespace std;
// Store the frequency of
// string for each index
int cnt[max_len];
// Compute and store frequencies
// for every index
void precompute(string s, string K)
{
int n = s.size();
for (int i = 0; i < n - 1; i++) {
cnt[i + 1]
= cnt[i]
+ (s.substr(i, K.size()) == K);
}
}
// Driver Code
int main()
{
string s = "ABCABCABABC";
string K = "ABC";
precompute(s, K);
vector<pair<int, int> > Q
= { { 1, 6 }, { 5, 11 } };
for (auto it : Q) {
cout << cnt[it.second - 1]
- cnt[it.first - 1]
<< endl;
}
return 0;
}
Java
// Java program to find
// frequency of a string K
// in a substring [L, R] in S
class GFG{
static int max_len = 100005;
// Store the frequency of
// string for each index
static int cnt[] = new int[max_len];
// Compute and store frequencies
// for every index
public static void precompute(String s,
String K)
{
int n = s.length();
for(int i = 0; i < n - 2; i++)
{
cnt[i + 1] = cnt[i];
if (s.substring(
i, i + K.length()).equals(K))
{
cnt[i + 1] += 1;
}
}
cnt[n - 2 + 1] = cnt[n - 2];
}
// Driver code
public static void main(String[] args)
{
String s = "ABCABCABABC";
String K = "ABC";
precompute(s, K);
int Q[][] = { { 1, 6 }, { 5, 11 } };
for(int it = 0; it < Q.length; it++)
{
System.out.println(cnt[Q[it][1] - 1] -
cnt[Q[it][0] - 1]);
}
}
}
// This code is contributed by divyesh072019
Python3
# Python3 Program to find
# frequency of a string K
# in a substring [L, R] in S
max_len = 100005
# Store the frequency of
# string for each index
cnt = [0] * max_len
# Compute and store frequencies
# for every index
def precompute(s, K):
n = len(s)
for i in range(n - 1):
cnt[i + 1] = cnt[i]
if s[i : len(K) + i] == K:
cnt[i + 1] += 1
# Driver Code
if __name__ == "__main__":
s = "ABCABCABABC"
K = "ABC"
precompute(s, K)
Q = [[1, 6], [5, 11]]
for it in Q:
print(cnt[it[1] - 1] -
cnt[it[0] - 1])
# This code is contributed by Chitranayal
C#
// C# program to find frequency of
// a string K in a substring [L, R] in S
using System.IO;
using System;
class GFG{
static int max_len = 100005;
// Store the frequency of
// string for each index
static int[] cnt = new int[max_len];
// Compute and store frequencies
// for every index
static void precompute(string s,string K)
{
int n = s.Length;
for(int i = 0; i < n - 2; i++)
{
cnt[i + 1] = cnt[i];
if (s.Substring(i, K.Length).Equals(K))
{
cnt[i + 1] += 1;
}
}
cnt[n - 2 + 1] = cnt[n - 2];
}
// Driver code
static void Main()
{
string s = "ABCABCABABC";
string K = "ABC";
precompute(s, K);
int[,] Q = { { 1, 6 }, { 5, 11 } };
for(int it = 0; it < Q.GetLength(0); it++)
{
Console.WriteLine(cnt[Q[it, 1] - 1] -
cnt[Q[it, 0] - 1]);
}
}
}
// This code is contributed by rag2127
JavaScript
<script>
// Javascript program to find
// frequency of a string K
// in a substring [L, R] in S
var max_len = 100005;
// Store the frequency of
// string for each index
var cnt = Array(max_len).fill(0);
// Compute and store frequencies
// for every index
function precompute(s, K)
{
var n = s.length;
for(var i = 0; i < n - 1; i++)
{
cnt[i + 1] = cnt[i] +
(s.substring(i, i + K.length) == K);
}
}
// Driver Code
var s = "ABCABCABABC";
var K = "ABC";
precompute(s, K);
var Q = [ [ 1, 6 ], [ 5, 11 ] ];
Q.forEach((it) => {
document.write(cnt[it[1] - 1] -
cnt[it[0] - 1] + "<br>");
});
// This code is contributed by itsok
</script>
Time Complexity: O( | S | + length of Q ), as every query is answered in O(1).
Auxiliary Space: O( |S| )
Similar Reads
Frequency of a substring in a string using pthread Given an input string and a substring. Find the frequency of occurrences of a substring in the given string using pthreads. Examples: Input: string = "man" substring = "dhimanman"Output: 2Input: string = "banana" substring = "nn"Output: 0Note: It is advised to execute the program in Linux based syst
6 min read
Queries for frequencies of characters in substrings Given a string s and Q number of queries. Each query Q consists of l and r and a character c. Find the frequency of character c in substring l to r. Examples: Input : s = geeksforgeeks 4 0 5 e 2 6 f 4 7 m 0 12 e Output : 2 1 0 4 Substring from 0 to 5 is geeksf. Here e occurs 2 times. Input : s = app
6 min read
Maximum length substring with highest frequency in a string Given a string. The task is to find the maximum occurred substring with a maximum length. These occurrences can overlap. Examples: Input: str = "abab" Output: ab "a", "b", "ab" are occur 2 times. But, "ab" has maximum length Input: str = "abcd" Output: a Approach: The idea is to store the frequency
5 min read
Frequency of a Substring in a String Given an input string and a pattern, the task is to find the frequency of occurrences of the string pattern in a given string. Examples: Input: pattern = "man", string = "dhimanman"Output: 2 Input: pattern = "nn", string = "Banana"Output: 0 Input: pattern = "aa", string = "aaaaa"Output : 4 Recommend
14 min read
Count Substrings with Frequencies Less than Maximum Digit Given a string S of length N. Then your task is to find the count of substrings such that, the frequency of each digit in that substring must be less than the maximum digit of substring. Examples:Input: S = 122321Output: 13Explanation: Below are some of those substrings: S[1, 2]: 12. Max element = 2
6 min read
Count of substrings of given string with frequency of each character at most K Given a string str, the task is to calculate the number of substrings of the given string such that the frequency of each element of the string is almost K. Examples: Input: str = "abab", K = 1Output: 7Explanation: The substrings such that the frequency of each character is atmost 1 are "a", "b", "a
6 min read
Queries to find the last non-repeating character in the sub-string of a given string Given a string str, the task is to answer Q queries where every query consists of two integers L and R and we have to find the last non-repeating character in the sub-string str[L...R]. If there is no non-repeating character then print -1.Examples: Input: str = "GeeksForGeeks", q[] = {{2, 9}, {2, 3}
11 min read
Recursive solution to count substrings with same first and last characters We are given a string S, we need to find count of all contiguous substrings starting and ending with same character. Examples : Input : S = "abcab" Output : 7 There are 15 substrings of "abcab" a, ab, abc, abca, abcab, b, bc, bca bcab, c, ca, cab, a, ab, b Out of the above substrings, there are 7 su
11 min read
Frequency of a string in an array of strings You are given a collection of strings and a list of queries. For every query there is a string given. We need to print the number of times the given string occurs in the collection of strings. Examples: Input : arr[] = {wer, wer, tyu, oio, tyu} q[] = {wer, tyu, uio}Output : 2 2 0Explanation : q[0] a
15 min read
Python - Count all prefixes in given string with greatest frequency Counting all prefixes in a given string with the greatest frequency involves identifying substrings that start from the beginning of the string and determining which appears most frequently. Using a Dictionary (DefaultDict)This approach uses defaultdict from the collections module to store prefix co
3 min read