index to store the last two occurrence indices for every character in the alphabet.res to store the result, which will be the sum of contributions of all characters.S, and for each character c at index i, update its last two occurrence indices in index.c using the formula (i - index[c][1]) * (index[c][1] - index[c][0]) and add it to res.index array to add the contributions of characters from their last occurrence to the end of the string.res.