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 frequency of character c in substring l to r.
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 = apple 2 0 4 e 1 2 p Output : 1 2
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Naive Approach: Run a loop from l to r for Q number of queries. Count occurrence of character and return count. Overall time complexity will be Q * O(|s|).
Efficient Approach:We can pre-compute the count for each character. Store count of each character in 2-D array. Return frequency of character from 0 to r minus frequency of character in range 0 to l in O(1). Overall time complexity will be Q * O(1).
2 1 0 4