String Range Queries to find the number of subsets equal to a given String

• Last Updated : 16 Aug, 2021

Given a string S of length N, and M queries of the following type:

Type 1: 1 L x,
Indicates update Lth index of string S by character ‘x’.
Type 2: 2 L R str
Find the number of subsets in range L to R
which is equal to the string str modulo 1000000007.
Constraints :
|S| <= 100000,
M <= 100000,
1 <= L, R <= |S|,
|str| <= 26,
All characters in str are unique,
S & str consisting of lowercase latin letters.

Examples:

Input : N = 16, M = 3, S = “geeekkksgskeegks”
type = 2: L = 1, R = 7, str = “gek”
type = 1: index = 2, character = ‘x’
type = 2: L = 1, R = 7, str = “gek”
Output : 9 6 4
query2 : No of subsets in string S i range [1…7] that is equal to gek is 9.
query1 : string S is changed to gxeekkksgskeegks after second query.
query2 : No of subsets in string S i range [1…7] that is equal to gek is 6.

Naive Approach :
Query type 1: We will calculate the frequency of each character of the query string in the range [L…R] and then multiply all the calculated frequencies to get the desired result.
Query type 2: We will replace the i’th character of the string with the given character.

Time complexity : 0(m*n)

Efficient Approach :

1. Using Segment Tree we can perform both operations in log(n) time. Every node of segment tree will contain frequency of characters in range [L..R].
2. The function build takes n*log(n) time to create a segment tree with every node containing the frequency of characters of some segment of the string.
3. The function get returns a vector containing frequency of all characters. Multiplication of all frequency of the given query string modulo 1e9+7 gives the desired result.
4. The function update decreases the frequency of character placed earlier and increases the frequency of new character present in the nodes of the segment tree by one.

Below is the implementation of the above approach:

Javascript


Output
2
1

Time complexity : 0(m*log(n)+n*log(n))
Auxiliary Space: O(n)

My Personal Notes arrow_drop_up