Suppose we have a string s whose length is n. We also have a list of queries Q, where Q[i] contains a pair (l, r). For each query we have to count number of different substrings of s in the inclusive range between l and r.
So, if the input is like s = "ppqpp" Q = [(1,1),(1,4),(1,1),(0,2)], then the output will be [1,8,1,5] because
For query (1, 1) the only substring is 'p' so output is 1
For query (1, 4) the substrings are 'p', 'q', 'pq', 'qp', 'pp', 'pqp', 'qpp' and 'pqpp', so output is 8
Again for query (1, 1) the only substring is 'p' so output is 1
For query (0, 2) the substrings are 'p', 'q', 'pp', 'pq', 'ppq', so the output is 8.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def kasai (s, suff, n): lcp =  * n inv =  * n for i in range (n): inv [suff [i]] = i k = 0 for i in range (n): if inv [i] == n-1: k = 0 continue j = suff [inv [i] + 1] while i + k <n and j + k <n and s [i + k] == s [j + k]: k += 1 lcp [inv [i]] = k if k> 0: k -= 1 return lcp def solve(s, Q): res =  for i in range (len(Q)): left, right = Q[i] sub = s [left: right + 1] length = right-left + 1 suffix = [[i, sub [i:]] for i in range (length)] suffix.sort (key = lambda x: x ) suff, suffix = [list (t) for t in zip (* suffix)] lcp = kasai (sub, suff, length) count = len (suffix ) for i in range (length-1): count += len (suffix [i + 1]) - lcp [i] res.append(count) return res s = "pptpp" Q = [(1,1),(1,4),(1,1),(0,2)] print(solve(s, Q))
[1, 8, 1, 5]