Here is an interesting solution that is extremely efficient. It looks at the problem from quite a different perspective.
q=int(input())
x=input()
y = x[0: q]
alphabet = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0,
'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r': 0, 's': 0, 't': 0,
'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0, ' ': 0}
letters = set(list(y))
for letter in letters:
alphabet[letter] += y.count(letter)
repeats = [i for i in list(alphabet.values()) if i > 1]
singles = len(y)
count = singles
for repeat in repeats:
count += ((repeat*(repeat - 1))/2)
What is going on here? Look at an artificial example where y = 'abbda efba hia jkla mbnop' and consider the character 'a'. How does it get counted?
1) It is counted each time it appears in the string. This is 5 times, and this is captured in the 'alphabet' dictionary. There is one pass through the unique characters within the string to get the count. This is less then or equal to 27 characters. I have included the space character. That has to be counted too!
2) The character 'a' is also counted in other ways by the original algorithm. It is counted when it appears on both ends of a sub string. In this case, for the first 'a' that appears we get the sub strings:
abba
abba efba
abba efba hia
abba efba hia jkla
For the second 'a' that appears there are three more such sub strings:
a efba
a efba hia
a efba hia jkla
And so on down the line. So we count 'a' 5 times for each time it appears in the string, but also count the 4 + 3 + 2 + 1 sub strings where it is on the ends. This is just r(r-1)/2 more counts for the letter 'a'. No need to loop when there is an analytic expression for the result. This is the basis for the algorithm's efficiency.