How Many Substrings?


Problem Statement :


Consider a string of n characters, s, of where each character is indexed from  to .

You are given  queries in the form of two integer indices:  and . For each query, count and print the number of different substrings of  in the inclusive range between  and .

Note: Two substrings are different if their sequence of characters differs by at least one. For example, given the string  aab, substrings  a and  a are the same but substrings  aa and  ab are different.

Input Format

The first line contains two space-separated integers describing the respective values of  and .
The second line contains a single string denoting .
Each of the  subsequent lines contains two space-separated integers describing the respective values of  and  for a query.

Constraints

String  consists of lowercase English alphabetic letters (i.e., a to z) only.
Subtasks

For  of the test cases, 
For  of the test cases, 
For  of the test cases, 
Output Format

For each query, print the number of different substrings in the inclusive range between index left and index  right on a new



Solution :



title-img


                            Solution in C :

In   C++  :








#include<stdio.h>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<iostream>
#include<cmath>
#include<ctime>
#include<set>
#include<map>
#include<vector>
#define pii pair<int,int>
#define fi first
#define se second
#define pb push_back
#define SZ(x) ((int)((x).size()))
#define rep(i,j,k) for(int i=(int)j;i<=(int)k;i++)
#define per(i,j,k) for(int i=(int)j;i>=(int)k;i--)
using namespace std;
typedef long long LL;
typedef double DB;
const DB pi=acos(-1.0);
const int N=100005;
int go[N<<1][26],fail[N<<1],len[N<<1],tot,last;
int n;
int cnt=0;
namespace seg{
int tag[N<<2];
LL sum[N<<2];
inline void Tag(int me,int l,int r,int v){
tag[me]+=v;
sum[me]+=(r-l+1)*1ll*v;
}
inline void down(int me,int l,int r){
if(tag[me]==0)return;
int mid=(l+r)>>1;
Tag(me<<1,l,mid,tag[me]);
Tag(me<<1|1,mid+1,r,tag[me]);
tag[me]=0;
}
void add(int me,int l,int r,int x,int y,int v){

if(l^r)down(me,l,r);
if(x<=l&&r<=y){
Tag(me,l,r,v);
return;
}
int mid=(l+r)>>1;
if(x<=mid)add(me<<1,l,mid,x,y,v);
if(y>mid)add(me<<1|1,mid+1,r,x,y,v);
sum[me]=sum[me<<1]+sum[me<<1|1];
}
LL ask(int me,int l,int r,int x,int y){
if(l^r)down(me,l,r);
if(x<=l&&r<=y)return sum[me];
int mid=(l+r)>>1;
LL ret=0;
if(x<=mid)ret+=ask(me<<1,l,mid,x,y);
if(y>mid)ret+=ask(me<<1|1,mid+1,r,x,y);
return ret;
}
void Do(int pre,int now,int L,int R){
if(L>R)return;
++cnt;
//printf("_%d %d %d %d\n",pre,now,L,R);
if(pre)add(1,1,n,pre-R+1,pre-L+1,-1);
add(1,1,n,now-R+1,now-L+1,1);
}
};
namespace lct{
int l[N<<2],r[N<<2],fa[N<<2];
int last[N<<2];
inline bool top(int x)
{return (!fa[x])||(l[fa[x]]!=x&&r[fa[x]]!=x);}
inline void left(int x){
int y=fa[x];int z=fa[y];
r[y]=l[x];if(l[x])fa[l[x]]=y;
fa[x]=z;if(l[z]==y)l[z]=x;
else if(r[z]==y)r[z]=x;
l[x]=y;fa[y]=x;
}
inline void right(int x){
int y=fa[x];int z=fa[y];
l[y]=r[x];if(r[x])fa[r[x]]=y;
fa[x]=z;if(l[z]==y)l[z]=x;else if(r[z]==y)r[z]=x;
r[x]=y;fa[y]=x;
}
inline void down(int x){
if(l[x])last[l[x]]=last[x];
if(r[x])last[r[x]]=last[x];
}
int q[N<<2];
inline void splay(int x){
q[q[0]=1]=x;
for(int k=x;!top(k);k=fa[k])q[++q[0]]=fa[k];
per(i,q[0],1)down(q[i]);
while(!top(x)){
int y=fa[x];int z=fa[y];
if(top(y)){
if(l[y]==x)right(x);else left(x);
}
else{
if(r[z]==y){
    if(r[y]==x)left(y),left(x);
    else right(x),left(x);
}
else{
    if(l[y]==x)right(y),right(x);
    else left(x),right(x);
}
}
}
}
void Access(int x,int cov){
int y=0;
for(;x;y=x,x=fa[x]){
splay(x);
down(x);
r[x]=0;

int L,R;
int z=x;
while(l[z])z=l[z];
L=len[fail[z]]+1;
splay(z);splay(x);
z=x;
while(r[z])z=r[z];
R=len[z];
splay(z);splay(x);
seg::Do(last[x],cov,L,R);
r[x]=y;
last[x]=cov;
}
}
void SetFa(int x,int y,int po){
fa[x]=y;
Access(x,po);
}
void split(int x,int y,int d){
splay(y);
down(y);
r[y]=0;
fa[d]=y;
splay(x);
fa[x]=d;
last[d]=last[x];
}
};
namespace sam{
void init(){
tot=last=1;
}
void expended(int x,int po){
int gt=++tot;len[gt]=len[last]+1;int p=last;last=tot;
for(;p&&(!go[p][x]);p=fail[p])go[p][x]=gt;
if(!p){
fail[gt]=1;
lct::SetFa(gt,1,po);
return;
}
int xx=go[p][x];
if(len[xx]==len[p]+1){
fail[gt]=xx;
lct::SetFa(gt,xx,po);
return;
}
int tt=++tot;
len[tt]=len[p]+1;
fail[tt]=fail[xx];
int dt=fail[xx];
fail[xx]=fail[gt]=tt;
lct::split(xx,dt,tt);
lct::SetFa(gt,tt,po);
rep(i,0,25)go[tt][i]=go[xx][i];
for(;p&&(go[p][x]==xx);p=fail[p])go[p][x]=tt;
}
};
int Q;
char str[N];
int qL[N];
vector<int>que[N];
LL ans[N];
void Main(){
rep(i,1,n){
sam::expended(str[i]-'a',i);
rep(j,0,que[i].size()-1){
int id=que[i][j];
ans[id]=seg::ask(1,1,n,qL[id],n);
}
}
}
void init(){
scanf("%d%d",&n,&Q);
scanf("%s",str+1);
rep(i,1,Q){
int r;scanf("%d%d",&qL[i],&r);
qL[i]++;r++;
que[r].pb(i);
}
sam::init();
}
void Output(){
rep(i,1,Q)printf("%lld\n",ans[i]);
}
int main(){
init();
Main();
Output();
return 0;
}










In   Java  :







//package hackerrank_smart;

import java.io.*;
import java.util.*;

public class Solution1 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = 
new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = 
new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int q = Integer.parseInt(st.nextToken());

        char[] str = br.readLine().toCharArray();

        List<Integer>[] queries = new List[n + 1];
        for (int i = 0; i < queries.length; i++) {
            queries[i] = new ArrayList<>();
        }

        int[] qL = new int[q + 1];
        for (int i = 1; i <= q; i++) {
            st = new StringTokenizer(br.readLine());

            int l = Integer.parseInt(st.nextToken());
            int r = Integer.parseInt(st.nextToken());

            qL[i] = l;
            qL[i]++;
            r++;
            queries[r].add(i);
        }

        fail = new int[n << 1];
        len = new int[n << 1];

        SegmentTree seg = new SegmentTree(n);
        Sam sam = new Sam(new Lct(seg));
        sam.init();

        long[] ans = new long[q + 1];
        for (int i = 1; i <= n; i++) {
            sam.expended(str[i - 1] - 'a', i);
            for (int id : queries[i]) {
                ans[id] = seg.ask(1, 1, n, qL[id], n);
            }
        }

        for (int i = 1; i <= q; i++) {
            long result = ans[i];
            bw.write(result + "\n");
        }

        bw.newLine();
        bw.close();
        br.close();
    }

    static class SegmentTree {
        int[] tag;
        long[] sum;
        int n;

        SegmentTree(int n) {
            this.n = n;
            tag = new int[n << 2];
            sum = new long[n << 2];
        }

        void tag(int me, int l, int r, int v) {
            tag[me] += v;
            sum[me] += (r - l + 1) * 1l * v;
        }

        void down(int me, int l, int r) {
            if (tag[me] == 0) {
                return;
            }
            int mid = (l + r) >> 1;
            tag(me << 1, l, mid, tag[me]);
            tag(me << 1 | 1, mid + 1, r, tag[me]);
            tag[me] = 0;
        }

        void add(int me, int l, int r, int x, int y, int v) {
            if ((l ^ r) != 0) {
                down(me, l, r);
            }
            if (x <= l && r <= y) {
                tag(me, l, r, v);
                return;
            }
            int mid = (l + r) >> 1;
            if (x <= mid) {
                add(me << 1, l, mid, x, y, v);
            }
            if (y > mid) {
                add(me << 1 | 1, mid + 1, r, x, y, v);
            }
            sum[me] = sum[me << 1] + sum[me << 1 | 1];
        }

        long ask(int me, int l, int r, int x, int y) {
            if ((l ^ r) != 0) {
                down(me, l, r);
            }
            if (x <= l && r <= y) {
                return sum[me];
            }
            int mid = (l + r) >> 1;
            long ret = 0;
            if (x <= mid) {
                ret += ask(me << 1, l, mid, x, y);
            }
            if (y > mid) {
                ret += ask(me << 1 | 1, mid + 1, r, x, y);
            }
            return ret;
        }

        void doAdd(int pre, int now, int L, int R) {
            if (L > R)
                return;

            if (pre != 0) {
                add(1, 1, n, pre - R + 1, pre - L + 1, -1);
            }
            add(1, 1, n, now - R + 1, now - L + 1, 1);
        }
    }

    static int[] fail;
    static int[] len;

    static class Lct {
        int[] l;
        int[] r;
        int[] fa;
        int[] last;
        int[] q;
        SegmentTree seg;

        Lct(SegmentTree seg) {
            this.seg = seg;
            l = new int[seg.n << 2];
            r = new int[seg.n << 2];
            fa = new int[seg.n << 2];
            last = new int[seg.n << 2];
            q = new int[seg.n << 2];
        }

        boolean top(int x) {
            return (fa[x] == 0) || (l[fa[x]] != x && r[fa[x]] != x);
        }

        void left(int x) {
            int y = fa[x];
            int z = fa[y];
            r[y] = l[x];
            if (l[x] != 0) {
                fa[l[x]] = y;
            }
            fa[x] = z;
            if (l[z] == y) {
                l[z] = x;
            } else if (r[z] == y) {
                r[z] = x;
            }
            l[x] = y;
            fa[y] = x;
        }

        void right(int x) {
            int y = fa[x];
            int z = fa[y];
            l[y] = r[x];
            if (r[x] != 0) {
                fa[r[x]] = y;
            }
            fa[x] = z;
            if (l[z] == y) {
                l[z] = x;
            } else if (r[z] == y) {
                r[z] = x;
            }
            r[x] = y;
            fa[y] = x;
        }

        void down(int x) {
            if (l[x] != 0) {
                last[l[x]] = last[x];
            }
            if (r[x] != 0) {
                last[r[x]] = last[x];
            }
        }

        void splay(int x) {
            q[q[0] = 1] = x;
            for (int k = x; !top(k); k = fa[k]) {
                q[++q[0]] = fa[k];
            }
            for (int i = (int) q[0]; i >= (int) 1; i--) {
                down(q[i]);
            }
            while (!top(x)) {
                int y = fa[x];
                int z = fa[y];
                if (top(y)) {
                    if (l[y] == x) {
                        right(x);
                    } else {
                        left(x);
                    }
                } else {
                    if (r[z] == y) {
                        if (r[y] == x) {
                            left(y);
                            left(x);
                        } else {
                            right(x);
                            left(x);
                        }
                    } else {
                        if (l[y] == x) {
                            right(y);
                            right(x);
                        } else {
                            left(x);
                            right(x);
                        }
                    }
                }
            }
        }

        void access(int x, int cov) {
            int y = 0;
            for (; x != 0; y = x, x = fa[x]) {
                splay(x);
                down(x);
                r[x] = 0;

                int z = x;
                while (l[z] != 0) {
                    z = l[z];
                }
                int L = len[fail[z]] + 1;
                splay(z);
                splay(x);
                z = x;
                while (r[z] != 0) {
                    z = r[z];
                }
                int R = len[z];
                splay(z);
                splay(x);
                seg.doAdd(last[x], cov, L, R);
                r[x] = y;
                last[x] = cov;
            }
        }

        void setFa(int x, int y, int po) {
            fa[x] = y;
            access(x, po);
        }

        void split(int x, int y, int d) {
            splay(y);
            down(y);
            r[y] = 0;
            fa[d] = y;
            splay(x);
            fa[x] = d;
            last[d] = last[x];
        }
    }

    static class Sam {
        int[][] go;
        int tot, last;
        Lct lct;

        Sam(Lct lct) {
            this.lct = lct;
            go = new int[lct.seg.n << 1][26];
        }

        void init() {
            tot = last = 1;
        }

        void expended(int x, int po) {
            int gt = ++tot;
            len[gt] = len[last] + 1;
            int p = last;
            last = tot;
            for (; p != 0 && (go[p][x] == 0); p = fail[p]) {
                go[p][x] = gt;
            }
            if (p == 0) {
                fail[gt] = 1;
                lct.setFa(gt, 1, po);
                return;
            }
            int xx = go[p][x];
            if (len[xx] == len[p] + 1) {
                fail[gt] = xx;
                lct.setFa(gt, xx, po);
                return;
            }
            int tt = ++tot;
            len[tt] = len[p] + 1;
            fail[tt] = fail[xx];
            int dt = fail[xx];
            fail[xx] = fail[gt] = tt;
            lct.split(xx, dt, tt);
            lct.setFa(gt, tt, po);
            for (int i = 0; i <= 25; i++) {
                go[tt][i] = go[xx][i];
            }
            for (; p != 0 && (go[p][x] == xx); p = fail[p]) {
                go[p][x] = tt;
            }
        }
    }
}










In   C  :









#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//#define DEBUG
#ifdef DEBUG
#define dprintf(...) fprintf(stderr, __VA_ARGS__)
#else
#define dprintf(...)
#endif
#define MAX_CHAR 27
  
struct SuffixTreeNode {
    struct SuffixTreeNode *children[MAX_CHAR];
    struct SuffixTreeNode *suffixLink;
    int start;
    int *end;
    int suffixIndex;
};
  
typedef struct SuffixTreeNode Node;
  
Node *root = NULL;
  
Node *lastNewNode = NULL;
Node *activeNode = NULL;
  
int activeEdge = -1;
int activeLength = 0;
  
int remainingSuffixCount = 0;
int leafEnd = -1;
int *rootEnd = NULL;
int *splitEnd = NULL;
int size = -1;

void resetTree() {
    root = NULL;;
    lastNewNode = NULL;
    activeNode = NULL;
    activeEdge = -1;
    activeLength = 0;
    remainingSuffixCount = 0;
    leafEnd = -1;
    rootEnd = NULL;
    splitEnd = NULL;
    size = -1;
}
  
Node *newNode(int start, int *end)
{
    Node *node =(Node*) malloc(sizeof(Node));
    int i;
    for (i = 0; i < MAX_CHAR; i++)
        node->children[i] = NULL;
    node->suffixLink = root;
    node->start = start;
    node->end = end;
    node->suffixIndex = -1;
    return node;
}
  
int edgeLength(Node *n) {
    if(n == root)
        return 0;
    return *(n->end) - (n->start) + 1;
}
  
int walkDown(Node *currNode)
{
    if (activeLength >= edgeLength(currNode))
    {
        activeEdge += edgeLength(currNode);
        activeLength -= edgeLength(currNode);
        activeNode = currNode;
        return 1;
    }
    return 0;
}
  
void extendSuffixTree(char* text, int pos)
{
    leafEnd = pos;
  
    remainingSuffixCount++;
  
    lastNewNode = NULL;
  
    while(remainingSuffixCount > 0) {
  
        if (activeLength == 0)
            activeEdge = pos; //APCFALZ
  
        if (activeNode->children[text[activeEdge]] == NULL)
        {
            //Extension Rule 2 (A new leaf edge gets created)
            activeNode->children[text[activeEdge]] =
                newNode(pos, &leafEnd);
  
            if (lastNewNode != NULL)
            {
                lastNewNode->suffixLink = activeNode;
                lastNewNode = NULL;
            }
        }
        else
        {
            Node *next = activeNode->children[text[activeEdge]];
            if (walkDown(next))
            {
                continue;
            }
            if (text[next->start + activeLength] == text[pos])
            {
                if(lastNewNode != NULL && activeNode != root)
                {
                    lastNewNode->suffixLink = activeNode;
                    lastNewNode = NULL;
                }
 
                activeLength++;
                break;
            }
  
            splitEnd = (int*) malloc(sizeof(int));
            *splitEnd = next->start + activeLength - 1;
  
            Node *split = newNode(next->start, splitEnd);
            activeNode->children[text[activeEdge]] = split;
  
            split->children[text[pos]] = newNode(pos, &leafEnd);
            next->start += activeLength;
            split->children[text[next->start]] = next;
  
            if (lastNewNode != NULL)
            {
                lastNewNode->suffixLink = split;
            }
  
            lastNewNode = split;
        }
  
        remainingSuffixCount--;
        if (activeNode == root && activeLength > 0)
        {
            activeLength--;
            activeEdge = pos - remainingSuffixCount + 1;
        }
        else if (activeNode != root)
        {
            activeNode = activeNode->suffixLink;
        }
    }
}
  
void print(char * text, int i, int j)
{
    int k;
    for (k=i; k<=j; k++)
        fprintf(stderr, "%c", text[k] + 'a' - 1);
}
void dprint(char * text, int i, int j)
{
#ifdef DEBUG
    print(text, i, j);
#endif
}
  
void setSuffixIndexByDFS(char *text, Node *n, int labelHeight)
{
    if (n == NULL)  return;
  
    if (n->start != -1)
    {
        dprint(text, n->start, *(n->end));
    }
    int leaf = 1;
    int i;
    for (i = 0; i < MAX_CHAR; i++)
    {
        if (n->children[i] != NULL)
        {
            if (leaf == 1 && n->start != -1)
                dprintf(" [%d]\n", n->suffixIndex);
  
            leaf = 0;
            setSuffixIndexByDFS(text, n->children[i], labelHeight +
                                edgeLength(n->children[i]));
        }
    }
    if (leaf == 1)
    {
        n->suffixIndex = size - labelHeight;
        dprintf(" [%d]\n", n->suffixIndex);
    }
}
  
int freeSuffixTreeByPostOrder(Node *n)
{
    if (n == NULL)
        return 0;
    int result = edgeLength(n);
    int i;
    for (i = 0; i < MAX_CHAR; i++)
    {
        if (n->children[i] != NULL)
        {
            result += freeSuffixTreeByPostOrder(n->children[i]);
            n->children[i] = NULL;
        }
    }
    if (n->suffixIndex == -1)
        free(n->end);
    free(n);
    return result;
}
  
void buildSuffixTree(char *text)
{
    size = strlen(text);
    int i;
    rootEnd = (int*) malloc(sizeof(int));
    *rootEnd = - 1;
  
    root = newNode(-1, rootEnd);
  
    activeNode = root;
    for (i=0; i<size; i++)
        extendSuffixTree(text, i);
    int labelHeight = 0;
    setSuffixIndexByDFS(text, root, labelHeight);
}
 
int main(){
    int n; 
    int q; 
    scanf("%d %d",&n,&q);
    char s[100002];
    scanf("%s",s);
    int sl = strlen(s);
    for (int i = 0; i < sl; i++) {
        s[i] = s[i] - 'a' + 1;
    }
    for(int a0 = 0; a0 < q; a0++){
        int left; 
        int right; 
        scanf("%d %d",&left,&right);
        char save = s[right+1];
        s[right+1] = 0;
        buildSuffixTree(&s[left]);
        printf("%d\n", freeSuffixTreeByPostOrder(root));
        resetTree();
        s[right+1] = save;
    }
    return 0;
}










In   Python3  :








#!/bin/python3

import sys


def substr(s):
    su=0
    n=len(s)
    f=0
    x=""
    i=0
    while i<n:
        if s[f:i+1] in s[0:i]:
            su+=f
            i+=1
        elif i!=f:
            f+=1
        else:
            f=i+1
            su+=f
            i+=1	
    return su

n,q = input().strip().split(' ')
n,q = [int(n),int(q)]
s = input().strip()
l=[]
for a0 in range(q):
    left,right = input().strip().split(' ')
    left,right = [int(left),int(right)]
    print(substr(s[left:right+1]))
                        








View More Similar Problems

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →