If we extend the sub-strings , , and to the end of the string , the score of the sub-string triplet won’t change. So, from now on, we will consider the sub-strings as suffixes for simplicity.
Build the suffix array and corresponding array of the string . The lexicographic order of the suffixes is known now. From now on, the suffix means the suffix of the suffix array. Let’s say, we have chosen three suffixes , , and from the suffix array where . It will be a good sub-string triplet surely. What will be the score of it? Here, we can observe that is the longest common prefix of the and suffix, is the longest common prefix of the and suffix. And we know from the statement that the score of the sub-string triplet is . Recall that the longest common prefix of any two suffixes is equal to the minimum value of the corresponding range in the array.
If we fix the suffix , we can calculate the summation of for all possible . Similarly, we can calculate the summation of for all possible . Then the summation of the scores of the good sub-string triplets where the suffix acts as will be . So, if we can calculate this thing for all possible , we are good to go.
Let’s say, in the array, the value is minimum in range , where = longest common prefix of the and suffix. It means, if we treat any suffix in range as and treat any suffix in range as , the value of will be for all of them. So, we can add to range. If we execute this process for each , eventually we will get for each . Similarly, we can also calculate for each . As we need to get the values after all the range updates, we can apply prefix sum to perform this in . We can find the range stated above for all the elements in by maintaining a monotonous stack. Note that, you need to be careful about overcounting while calculating the and .