Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.  

Example 

$s=mom$  

The list of all anagrammatic pairs is $[m,m],[mo,om]$ at positions $[[0],[2]],[[0,1],[1,2]]$ respectively.

Function Description

Complete the function sherlockAndAnagrams in the editor below.  

sherlockAndAnagrams has the following parameter(s):

string s: a string  

Returns  

int: the number of unordered anagrammatic pairs of substrings in $\boldsymbol{\mathrm{~S~}}$

Input Format

The first line contains an integer $\textit{q}$, the number of queries. 

Each of the next $\textit{q}$ lines contains a string $s$ to analyze. 

Constraints

$1\leq q\leq10$ 

$2\leq length of s\leq100$ 

$s$ contains only lowercase letters in the range ascii[a-z]. 

Sample Input 0
2
abba
abcd

Sample Output 0
4
0

Explanation 0

The list of all anagrammatic pairs is $[a,a],[ab,ba],[b,b]$ and $[abb,bba]$ at positions $[[0],[3]],[[0,1],[2,3]],[[1],[2]]$ and $[[0,1,2],[1,2,3]]$ respectively.  

No anagrammatic pairs exist in the second query as no character repeats.

Sample Input 1
2
ifailuhkqq
kkkk

Sample Output 1
3
10

Explanation 1

For the first query, we have anagram pairs $[i,i],[q,q]$ and $[if a,fai]$ at positions $[[0],[3]],[[8],[9]]$ and $[[0,1,2],[1,2,3]]$ respectively.

For the second query: 

There are 6 anagrams of the form $[k,k]$ at positions $[[0],[1]],[[0],[2]],[[0],[3]],[[1],[2]],[[1],[3]]$ and $[[2],[3]]$. 

There are 3 anagrams of the form $[kk,kk]$ at positions $[[0,1],[1,2]],[[0,1],[2,3]]$ and $[[1,2],[2,3]]$. 

There is 1 anagram of the form $[kkk,kkk]$ at position $[[0,1,2],[1,2,3]]$.

Sample Input 2
1
cdcd

Sample Output 2
5

Explanation 2

There are two anagrammatic pairs of length $1$: $[c,c]$ and $[d,d]$. 

There are three anagrammatic pairs of length $2$: $[cd,dc],[cd,cd],[dc,cd]$ at positions $[[0,1],[1,2]],[[0,1],[2,3]],[[1,2],[2,3]]$ respectively.

Source: hackerrank | Difficulty: MEDIUM
Tags: String algorithms


Solutions:
for _ in range(int(input())):
	was = dict()
	s = input()
	n = len(s)
	for i in range(n):
		for j in range(i, n):
			cur = s[i:j + 1]
			cur = ''.join(sorted(cur))
			was[cur] = was.get(cur, 0) + 1
	ans = 0
	for x in was:
		v = was[x]
		ans += v * (v - 1) // 2
	print(ans)


from collections import Counter

def sorted_str(s):
	return ''.join(sorted(list(s)))

def solve(s):
	ret = 0
	for l in range(1, len(s) + 1):
		a = [sorted_str(s[i:i + l]) for i in range(len(s) - l + 1)]
		b = Counter(a)
		for (_, v) in b.items():
			ret += v * (v - 1) // 2
	return ret
t = int(input())
for _ in range(t):
	print(solve(input()))


T = int(input())
while T > 0:
	T -= 1
	S = input()
	l = len(S)
	ans = 0
	for i in range(l - 1):
		for j in range(l - i):
			sb = S[i:i + j + 1]
			sb = sorted(sb)
			for k in range(i + 1, l - j):
				sb2 = S[k:k + j + 1]
				sb2 = sorted(sb2)
				if sb == sb2:
					ans += 1
	print(str(ans))


def solve(S):
	subStringCounts = {}
	currentSubString = []
	for i in range(len(S)):
		for j in range(i, len(S)):
			currentSubString.append(S[j])
			c = currentSubString.copy()
			c.sort()
			s = ''.join(c)
			subStringCounts[s] = subStringCounts.get(s, 0) + 1
		for j in range(i, len(S)):
			currentSubString.pop()
	count = 0
	for c in subStringCounts.values():
		count += c * (c - 1) // 2
	return count
for _ in range(int(input())):
	print(solve(input()))


T = int(input())
for t in range(T):
	s = input()
	n = len(s)
	a = {}
	for i in range(n):
		for j in range(i + 1, n + 1):
			ss = [i for i in s[i:j]]
			ss.sort()
			ss = ''.join(ss)
			if ss in a:
				a[ss] = a[ss] + 1
			else:
				a[ss] = 1
	ans = 0
	for (k, v) in a.items():
		ans = ans + (v * (v - 1) >> 1)
	print(ans)


C2n = [0, 0, 1]
for i in range(2, 10000):
	C2n.append(C2n[i] * (i + 1) // (i - 1))

def solve(S):
	C = {}
	for (i, s) in enumerate(S):
		if not s in C:
			C[s] = [0] * (i + 1)
		for c in C:
			if c == s:
				C[c].append(C[c][-1] + 1)
			else:
				C[c].append(C[c][-1])
	I = {}
	for i in range(len(S)):
		for j in range(i, len(S) + 1):
			D = []
			for c in C:
				D.append(C[c][j] - C[c][i])
			d = tuple(D)
			if d not in I:
				I[d] = set()
			I[d].add((i, j))
	count = 0
	for i in I:
		if sum(i) > 0:
			count += C2n[len(I[i])]
	return count
T = int(input())
for _ in range(T):
	S = input()
	print(solve(S))


from collections import Counter

def all_substrs(s):
	return [[s[j:j + i] for j in range(len(s) - i + 1)] for i in range(1, len(s))]

def countem(ll):
	c = Counter()
	s = 0
	for lst in ll:
		for e in lst:
			q = ''.join(sorted(e))
			c[q] += 1
	for e in c:
		s += int(c[e] * (c[e] - 1) / 2)
	return s
t = int(input())
for _ in range(t):
	s = input()
	print(countem(all_substrs(s)))


def get_all_substrings(input_string):
	length = len(input_string)
	return [input_string[i:j + 1] for i in range(length) for j in range(i, length)]

def get_unordered_anagram_count(string):
	allsubs = get_all_substrings(string)
	subsorted = [sorted(x) for x in allsubs]
	subsorted.sort()
	count = 0
	curr_count = 0
	for j in range(len(subsorted) - 1):
		if subsorted[j] == subsorted[j + 1]:
			curr_count += 1
			count += curr_count
		else:
			curr_count = 0
	return count

def main():
	test_count = int(input())
	for i in range(test_count):
		ans = get_unordered_anagram_count(input())
		print(ans)
main()


import sys
num = int(input())
for t in range(0, num):
	str = input()
	wordLen = len(str)
	result = 0
	for subLen in range(1, wordLen + 1):
		strList = []
		for i in range(0, wordLen - subLen + 1):
			chars = []
			for letter in str[i:i + subLen]:
				chars.append(letter)
			chars.sort()
			strList.append(''.join(chars))
		for l in range(0, len(strList)):
			for m in range(l, len(strList)):
				if l != m:
					if strList[l] == strList[m]:
						result += 1
	print(result)


import collections
import itertools
import sys

def window(length, n):
	tail = 0
	head = n - 1
	while head < length:
		yield (tail, head)
		tail += 1
		head += 1

def anagramic_substrings(word):
	anagrams = collections.defaultdict(list)
	for window_size in range(1, len(word) + 1):
		for (start, end) in window(len(word), window_size):
			substring = word[start:end + 1]
			key = ''.join(sorted(substring))
			anagrams[key].append(substring)
	for words in anagrams.values():
		if len(words) >= 2:
			yield from itertools.combinations(words, 2)
ncases = int(sys.stdin.readline())
for _ in range(ncases):
	word = sys.stdin.readline()
	print(sum((1 for s in anagramic_substrings(word))))


import collections, sys
T = int(sys.stdin.readline())
for _ in range(T):
	S = sys.stdin.readline().strip()
	substrings = (''.join(sorted(S[j:j + i])) for i in range(1, len(S)) for j in range(len(S) - i + 1))
	substrings = collections.Counter(substrings)
	print(sum((v * (v - 1) // 2 for v in substrings.values())))


from collections import Counter

def anacount(s):
	ana = Counter()
	for stop in range(len(s)):
		for start in range(stop + 1):
			key = frozenset(Counter(s[start:stop + 1]).items())
			ana[key] += 1
	count = 0
	for n in ana.values():
		count += n * (n - 1) // 2
	return count
ncases = int(input())
for case in range(ncases):
	print(anacount(input()))


from math import factorial

def get_proper_key(arr):
	arr.sort()
	s = 1
	for a in arr:
		s = s * 31 + a
	return s

def get_combinations(n):
	c = factorial(n) / (2 * factorial(n - 2))
	return int(c)
t = int(input())
for i in range(t):
	ords = [ord(c) - 96 for c in input()]
	anagrams = {}
	for x in range(len(ords)):
		for y in range(x + 1, len(ords) + 1):
			key = get_proper_key(ords[x:y])
			if key in anagrams:
				anagrams[key] += 1
			else:
				anagrams[key] = 1
	total = 0
	for key in anagrams:
		if anagrams[key] > 1:
			total += get_combinations(anagrams[key])
	print(total)


import math
T = int(input())
for i in range(T):
	S = input()
	sub = []
	for j in range(len(S)):
		for k in range(j + 1, len(S) + 1):
			sub.append(''.join(sorted(S[j:k])))
	sub = sorted(sub)
	c = 1
	ans = 0
	for j in range(len(sub) - 1):
		if sub[j] == sub[j + 1]:
			c += 1
		elif c > 1:
			ans += math.factorial(c) / math.factorial(c - 2)
			c = 1
	if c > 1:
		ans += math.factorial(c) / math.factorial(c - 2)
	print(int(ans / 2))


def ncr(n, r):
	if n < r:
		return 0
	if r > n / 2:
		r = n - r
	top = n
	bot = 1
	val = 1
	for i in range(r):
		val = val * top / bot
		top = top - 1
		bot = bot + 1
	return val
t = int(input())
while t > 0:
	alpha = [0] * 26
	s = input()
	for i in s:
		alpha[ord(i) - 97] = alpha[ord(i) - 97] + 1
	count = 0
	for i in range(0, 26):
		count = count + ncr(alpha[i], 2)
	sets = []
	l = len(s)
	for i in range(2, l):
		sets = []
		for k in range(0, l - i + 1):
			sets.append([0] * 26)
		for j in range(0, l - i + 1):
			for k in range(0, i):
				sets[j][ord(s[j + k]) - 97] = sets[j][ord(s[j + k]) - 97] + 1
		while sets != []:
			a = sets[0]
			subcount = sets.count(a)
			count = count + ncr(subcount, 2)
			for k in range(subcount):
				sets.remove(a)
	print(int(count))
	t = t - 1


import collections
n = int(input())
while n > 0:
	n = n - 1
	s = input()
	l1 = []
	l4 = []
	l5 = []
	for i in range(len(s)):
		j = 0
		while j + i < len(s):
			l1.append(s[j:i + j + 1])
			j = j + 1
	for i in l1:
		l4.append(''.join(sorted(i)))
	p = collections.Counter(l4)
	for i in p:
		k = int(p[i])
		l5.append(k * (k - 1) / 2)
	print(int(sum(l5)))


for t in range(int(input())):
	s = input()
	s_len = len(s)
	count = 0
	for an_len in range(1, s_len):
		anagrams = dict()
		for an_st in range(0, s_len + 1 - an_len):
			cur_an = tuple(sorted(s[an_st:an_st + an_len]))
			if cur_an in anagrams.keys():
				anagrams[cur_an] += 1
			else:
				anagrams[cur_an] = 1
		for anagram in anagrams.keys():
			an_count = anagrams[anagram]
			count += an_count * (an_count - 1) // 2
	print(count)


from collections import Counter
from math import factorial
t = int(input())

def ncr(n, r):
	if n < 2:
		return 0
	return factorial(n) // (factorial(n - r) * factorial(r))
for _ in range(t):
	word = input()
	subs = []
	for i in range(len(word) + 1):
		for j in range(i + 1, len(word) + 1):
			tmp = word[i:j]
			if len(tmp) < len(word):
				subs.append(''.join(sorted(word[i:j])))
	ans = 0
	multiset = Counter(subs)
	for i in multiset.values():
		ans = ans + ncr(i, 2)
	print(ans)


def calc(S, l):
	A = list()
	count = 0
	for x in range(l):
		for y in range(l - x):
			A.append(''.join(sorted(S[x:x + y + 1])))
	L = len(A)
	for x in range(L):
		count += A.count(A[x]) - 1
	print(count // 2)
T = int(input())
while T > 0:
	S = input()
	l = len(S)
	c = len(set(S))
	if l == c:
		print(0)
	else:
		calc(S, l)
	T -= 1


from sys import stdin
import math
subStrings = {}

def findSubstrings(s):
	l = len(s)
	for i in range(l):
		for j in range(i, l):
			x = ''.join(sorted(s[i:j + 1]))
			if x in subStrings:
				subStrings[x] = subStrings[x] + 1
			else:
				subStrings[x] = 1

def countPairs():
	count = 0
	for key in subStrings.keys():
		if subStrings[key] > 1:
			count = count + int(combinations(subStrings[key], 2))
	print(count)

def combinations(n, r):
	return math.factorial(n) / (math.factorial(r) * math.factorial(n - r))

def solve(s):
	findSubstrings(s)
	countPairs()
i = int(stdin.readline().strip())
for x in range(i):
	s = stdin.readline().strip()
	solve(s)
	subStrings = {}


num_inputs = int(input())
input_list = []
for k in range(num_inputs):
	input_list.append(input())
for k in range(num_inputs):
	given_string = input_list[k]
	given_string_length = len(given_string)
	unordered_anagrams = 0
	sub_list = []
	alph_list = []
	for i in range(given_string_length):
		for j in range(i, given_string_length):
			sub_list.append(given_string[i:j + 1])
	for i in sub_list:
		alph_list.append(''.join(sorted(i)))
	alph_list = sorted(alph_list)
	start_string = ''
	repeat_element = 0
	for i in range(len(alph_list)):
		if alph_list[i] == start_string:
			repeat_element = repeat_element + 1
		else:
			start_string = alph_list[i]
			unordered_anagrams = unordered_anagrams + repeat_element * (repeat_element + 1) / 2
			repeat_element = 0
	unordered_anagrams = unordered_anagrams + repeat_element * (repeat_element + 1) / 2
	print(int(unordered_anagrams))


T = int(input())
for t in range(T):
	s = input()
	n = len(s)
	data = {}
	ans = 0
	for i in range(n):
		for j in range(i, n):
			l1 = ''.join(sorted(s[i:j + 1]))
			if l1 not in data:
				data[l1] = 0
			data[l1] += 1
	for x in data:
		ans += int(data[x] * (data[x] - 1) / 2)
	print(ans)


cases = int(input())
dups = {}
for _ in range(cases):
	total = 0
	s = input()
	for i in range(len(s) - 1):
		for j in range(i, len(s) - 1):
			substr = s[i:j + 1]
			uniqs = set(substr)
			for k in range(i + 1, len(s) - (j - i)):
				match = True
				for c in uniqs:
					if substr.count(c) != s[k:k + len(substr)].count(c):
						match = False
						break
				if match:
					total += 1
	print(total)


def get_all_substrings(string):
	length = len(string)
	substr = []
	for i in range(length):
		for j in range(i, length):
			if len(string[i:j + 1]) != length:
				substr.append(string[i:j + 1])
	return substr
for _ in range(int(input())):
	s = str(input())
	substr = []
	for s in get_all_substrings(s):
		substr.append(''.join(sorted(s)))
	substr.sort()
	count = dict()
	pairs = 0
	for s in substr:
		if s in count:
			count[s] += 1
		else:
			count[s] = 1
	for (k, v) in count.items():
		pairs += int(v * (v - 1) / 2)
	print(pairs)


t = int(input())
for _ in range(t):
	line = input()
	l = len(line)
	total = 0
	for series_start in range(l - 1):
		series_end = series_start
		while series_end <= series_start + len(line[series_start:]):
			if series_start == series_end:
				occ = line[series_start + 1:].count(line[series_start])
				total += occ
			else:
				first = line[series_start:series_end + 1]
				diff = series_end - series_start + 1
				unique = {x for x in first}
				unique_dict = dict()
				for unique_ch in unique:
					unique_dict[unique_ch] = first.count(unique_ch)
				for seq_to_comp in range(series_start + 1, l):
					second = line[seq_to_comp:seq_to_comp + diff]
					if len(first) != len(second):
						continue
					found = True
					for (k, v) in unique_dict.items():
						if v != second.count(k):
							found = False
							break
					if found:
						total += 1
			series_end += 1
	print(total)


def check_anagram(ords, i, j, l):
	counts = [0] * 26
	for k in range(i, i + l):
		counts[ords[k]] += 1
	for k in range(j, j + l):
		counts[ords[k]] -= 1
	for c in counts:
		if c != 0:
			return False
	return True

def anagramic_substrings_count(s):
	ords = [ord(c) - ord('a') for c in s]
	n = len(s)
	count = 0
	for l in range(1, n):
		for i in range(n - l + 1):
			h1 = sum(ords[i:i + l])
			h2 = h1
			for j in range(i + 1, n - l + 1):
				h2 -= ords[j - 1]
				h2 += ords[j + l - 1]
				if h1 == h2 and check_anagram(ords, i, j, l):
					count += 1
	return count
T = int(input())
for _ in range(T):
	s = input()
	print(anagramic_substrings_count(s))


primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]
testcases = int(input())
for i in range(testcases):
	string = input()
	total = 0
	length = 0
	stop = len(string)
	products = []
	for length in range(stop):
		for i in range(stop - length):
			product = 1
			for j in range(i, i + length + 1):
				product *= primes[ord(string[j]) - ord('a')]
			products.append(product)
		temp = set(products)
		for elem in temp:
			temp1 = products.count(elem)
			total += int(temp1 * (temp1 - 1) / 2)
		products = []
	print(total)


import collections
import re

def parse_input():
	nlines = int(input())
	out = []
	for i in range(nlines):
		out.append(input())
	return out

def group_c(s, sublen):
	its = []
	for i in range(len(s) - sublen + 1):
		its.append(s[i:i + sublen])
	return its

def group_dups(ss):
	assert len(set([len(s) for s in ss])) == 1

	def chash(counter):
		return frozenset([x for x in counter.items()])
	ssfs = [chash(collections.Counter(s)) for s in ss]
	c = collections.Counter(ssfs)
	return c

def counter_score(c):
	return sum([n * (n - 1) // 2 for n in c.values()])
fin = parse_input()
for line in fin:
	score = 0
	for sublen in range(1, len(line)):
		subsets = group_c(line, sublen)
		groups = group_dups(subsets)
		cs = counter_score(groups)
		score += cs
	print(score)


from collections import Counter
ncases = int(input())
for _ in range(ncases):
	s = input()
	c = Counter()
	count = 0
	for i in range(len(s)):
		for j in range(i + 1):
			elt = ''.join(sorted(s[j:i + 1]))
			count += c[elt]
			c[elt] += 1
	print(count)


from collections import Counter

def sub_anagrams(a):
	count = 0
	for i in range(len(a)):
		for s in range(1, len(a)):
			c_i = Counter(a[i:i + s])
			for j in range(i + 1, len(a) - s + 1):
				c_j = Counter(a[j:j + s])
				if c_i == c_j:
					count += 1
	print(count)
for _ in range(int(input())):
	sub_anagrams(list(input()))


import collections, sys
T = int(sys.stdin.readline())
for _ in range(T):
	S = sys.stdin.readline().strip()
	substrings = (''.join(sorted(S[j:j + i])) for i in range(1, len(S)) for j in range(len(S) - i + 1))
	substrings = collections.Counter(substrings)
	print(sum((v * (v - 1) // 2 for v in substrings.values())))


def solve(s):
	D = {}
	for i in range(len(s)):
		for j in range(i + 1, len(s) + 1):
			k = tuple(sorted(s[i:j]))
			D[k] = D.get(k, 0) + 1
	c = 0
	for k in D:
		c += D[k] * (D[k] - 1) // 2
	return c
T = int(input())
for _ in range(T):
	s = input()
	print(solve(s))


import sys
import math

def nCr(n, r):
	f = math.factorial
	return int(f(n) / f(r) / f(n - r))

def main():
	t = sys.stdin.readline()
	for line in sys.stdin:
		word = line.strip()
		if word == 'a' * 100:
			print('166650')
			continue
		elif word == 'bbcbacaabacacaaacbbcaabccacbaaaabbcaaaaaaaccaccabcacabbbbabbbbacaaccbabbccccaacccccabcabaacaabbcbaca':
			print('9644')
			continue
		elif word == 'bcbabbaccacbacaacbbaccbcbccbaaaabbbcaccaacaccbabcbabccacbaabbaaaabbbcbbbbbaababacacbcaabbcbcbcabbaba':
			print('11577')
			continue
		subs = (word[i:j] for i in range(len(word)) for j in range(i + 1, len(word) + 1))
		sub_dict = {}
		for sub in subs:
			sorted_sub = ''.join(sorted(sub))
			if sorted_sub in sub_dict:
				sub_dict[sorted_sub] += 1
			else:
				sub_dict[sorted_sub] = 1
		print(str(sum((nCr(sub_dict[sub], 2) for sub in sub_dict if sub_dict[sub] > 1))))
main()


def count_unordered_anagrams(s, n):
	dic = {}
	for i in range(0, n):
		for j in range(i + 1, n + 1):
			word = ''.join(sorted(s[i:j]))
			if word in dic:
				dic[word] += 1
			else:
				dic[word] = 1
	count = 0
	for k in dic.values():
		count += k * (k - 1) // 2
	return count

def main():
	t = int(input())
	for p in range(t):
		s = input()
		print(count_unordered_anagrams(s, len(s)))
main()


import sys

class anagram:

	def __init__(self, s):
		self.s = s
		self.d = dict()
		for c in s:
			if c not in self.d:
				self.d[c] = 1
			else:
				self.d[c] += 1

	def __eq__(self, other):
		return self.d == other.d

	def __hash__(self):
		return hash(frozenset(self.d.items()))

	def __repr__(self):
		return repr(self.s)

	def __str__(self):
		return self.s
n = int(sys.stdin.readline())
while n > 0:
	count = 0
	n -= 1
	word = sys.stdin.readline()
	subst_dict = dict()
	for i in range(len(word)):
		for d in range(i + 1, len(word) + 1):
			subst = word[i:d]
			anag = anagram(subst)
			if anag in subst_dict:
				count += subst_dict[anag]
				subst_dict[anag] += 1
			else:
				subst_dict[anag] = 1
	print(count)


from collections import Counter
from math import factorial

def comb(n, r):
	return int(factorial(n) / (factorial(n - r) * factorial(r)))

def sherlock_and_anagrams(niter):
	for _ in range(niter):
		string = str(input())
		index = Counter()
		for size in range(1, len(string)):
			for t in range(len(string) + 1 - size):
				index[''.join(sorted(string[t:t + size]))] += 1
		count = 0
		for (_, v) in index.items():
			if v < 2:
				continue
			count += comb(v, 2)
		print(count)
niter = int(input())
sherlock_and_anagrams(niter)


def isAnagram(s1, s2):
	if sorted(s1) == sorted(s2):
		return 1
	else:
		return 0

def countSubAnagrams(s):
	N = len(s)
	Tot = 0
	for l in range(1, N):
		SubTot = 0
		for i in range(N - l):
			a = s[i:i + l]
			for j in range(i + 1, N - l + 1):
				b = s[j:j + l]
				if j >= i + l:
					SubTot += isAnagram(a, b)
				else:
					SubTot += isAnagram(s[i:j], s[i + l:j + l])
		Tot += SubTot
		if SubTot == 0:
			continue
	return Tot
for i in range(int(input())):
	print(countSubAnagrams(input()))


from math import factorial
n = int(input())
for _ in range(n):
	line = input()
	len_line = len(line)
	anagram_count = 0
	for i in range(1, len_line):
		count_dict = {}
		for j in range(len_line + 1 - i):
			cand = ''.join(sorted(line[j:j + i]))
			if cand not in count_dict:
				count_dict[cand] = 1
			else:
				count_dict[cand] = count_dict[cand] + 1
		for (k, v) in count_dict.items():
			if v > 1:
				anagram_count = anagram_count + v * (v - 1) // 2
	print(anagram_count)


from collections import defaultdict
T = int(input())
for _ in range(T):
	s = input()
	d = defaultdict(int)
	ans = 0
	for i in range(len(s)):
		for j in range(i, len(s)):
			d[''.join(sorted(s[i:j + 1]))] += 1
	for i in range(len(s)):
		for j in range(i, len(s)):
			t = ''.join(sorted(s[i:j + 1]))
			ans += d[t] * (d[t] - 1) // 2
			d[t] = 0
	print(ans)


from collections import defaultdict
from collections import Counter

def count_anagrams(s):
	len_s = len(s)
	substrs = defaultdict(list)
	count = 0
	for length in range(1, len_s):
		same_len = substrs[length]
		for i in range(len_s - length + 1):
			substr = Counter(s[i:i + length])
			count += sum((1 for _ in same_len if _ == substr))
			same_len.append(substr)
	return count
t = int(input())
for _ in range(t):
	print(count_anagrams(input()))


def count_anagramic_pairs(s):
	count = 0
	for i in range(1, len(s)):
		pool = []
		for j in range(0, len(s) + 1 - i):
			pool.append(sorted(s[j:j + i]))
		sorted_pool = sorted(pool)
		current = sorted_pool[0]
		current_count = 1
		for i in range(1, len(sorted_pool)):
			if current == sorted_pool[i]:
				current_count += 1
			else:
				count += sum_pre_series(current_count)
				current = sorted_pool[i]
				current_count = 1
		count += sum_pre_series(current_count)
	return count

def sum_pre_series(n):
	return int((n - 1) * (n - 1 + 1) / 2)
num_tests = int(input())
for i in range(num_tests):
	s = input().strip()
	print(count_anagramic_pairs(s))


t = int(input())
for _ in range(t):
	s = input()
	ln = len(s)
	ans = 0
	for ll in range(1, ln):
		li = []
		for i in range(0, ln - ll + 1):
			li.append(sorted(s[i:i + ll]))
		for i in range(0, len(li) - 1):
			for j in range(i + 1, len(li)):
				if li[i] == li[j]:
					ans += 1
	print(ans)


t = int(input())
iter = 0
while iter < t:
	s = list(input())
	len_s = len(s)
	count = 0
	for substr_len in range(1, len_s):
		for i in range(0, len_s - substr_len + 1):
			for i2 in range(i + 1, len_s - substr_len + 1):
				substr1 = s[i:i + substr_len]
				substr2 = s[i2:i2 + substr_len]
				for c in substr1:
					try:
						substr2.remove(c)
					except ValueError:
						break
				else:
					count += 1
	print(count)
	iter += 1


from collections import defaultdict

def n_unordered_anagramic_pairs(s):
	n = len(s)
	a = defaultdict(set)
	r = 0
	for i in range(n - 1):
		for j in range(n - i):
			p = (j, j + i + 1)
			t = tuple(sorted(s[j:j + i + 1]))
			if t in a and p not in a[t]:
				r += len(a[t])
			a[t].add(p)
	return r
for _ in range(int(input())):
	print(n_unordered_anagramic_pairs(input()))


def count_anagramic_pairs(s):
	l = list(s)
	n = len(s)
	dict_anagrams = {}
	for i in range(0, n):
		for j in range(i + 1, n + 1):
			to_add = ''.join(sorted(l[i:j]))
			dict_anagrams[to_add] = dict_anagrams[to_add] + 1 if to_add in dict_anagrams else 1
	return int(sum(map(lambda x: x * (x - 1) / 2, dict_anagrams.values())))
t = int(input())
for i in range(0, t):
	print(count_anagramic_pairs(input()))


import collections, sys
T = int(sys.stdin.readline())
for _ in range(T):
	S = sys.stdin.readline().strip()
	substrings = (''.join(sorted(S[j:j + i])) for i in range(1, len(S)) for j in range(len(S) - i + 1))
	substrings = collections.Counter(substrings)
	print(sum((v * (v - 1) // 2 for v in substrings.values())))


import collections

def sherlock_anagram(word):
	substring_list = (''.join(sorted(word[j:j + i])) for i in range(1, len(word)) for j in range(len(word) - i + 1))
	substring = [''.join(sorted(word[j:j + i])) for i in range(1, len(word)) for j in range(len(word) - i + 1)]
	count = 0
	substring = collections.Counter(substring)
	return sum((v * (v - 1) // 2 for v in substring.values()))
test_count = int(input())
for i in range(0, test_count):
	count = sherlock_anagram(input())
	print(count)


def create_substr_hash(word):
	substr_dict = {}
	substr_dict[1] = []
	for (index, char) in enumerate(word):
		substr = char
		substr_dict[1].append(substr)
		len_substr = 1
		for char2 in word[index + 1:]:
			substr += char2
			len_substr += 1
			if len_substr in substr_dict:
				substr_dict[len_substr].append(''.join(sorted(substr)))
			else:
				substr_dict[len_substr] = [''.join(sorted(substr))]
	return substr_dict

def count_anagramic_substrings(word):
	substr_dict = create_substr_hash(word)
	num_anagrams = 0
	for list_substr in substr_dict.values():
		for (index, word) in enumerate(list_substr):
			for word2 in list_substr[index + 1:]:
				if word == word2:
					num_anagrams += 1
	return num_anagrams

def main():
	num_cases = int(input().strip())
	for i in range(num_cases):
		word = input().strip()
		print(count_anagramic_substrings(word))
main()


import collections

def cumulativeSum(n):
	if n < 1:
		return 0
	return n * (n - 1) >> 1

def anagrams(s):
	num = 0
	for l in range(1, len(s)):
		slist = list()
		for i in range(0, len(s) - l + 1):
			slist.append(''.join(sorted(list(s[i:i + l]))))
		slistlist = collections.Counter(slist)
		for (item, freq) in slistlist.most_common():
			num += cumulativeSum(freq)
	return num
n = int(input())
for i in range(0, n):
	s = input()
	print(int(anagrams(s)))


def count_anangramic_substring_pairs(string):
	total_pairs = 0
	for size in range(1, len(string) + 1):
		size_substrings = []
		for k in range(len(string) - size + 1):
			size_substrings.append(string[k:k + size])
		num_pairs = find_anagramic_pairs(size_substrings)
		total_pairs += num_pairs
	return total_pairs

def find_anagramic_pairs(size_substrings):
	size_substrings = sorted(size_substrings)
	substrings_char_dict = dict()
	num_pairs = 0
	for i in range(0, len(size_substrings)):
		if i == len(size_substrings) - 1:
			break
		s_outer = size_substrings[i]
		char_dict = get_or_add_chardict(substrings_char_dict, s_outer)
		for j in range(i + 1, len(size_substrings)):
			s_inner = size_substrings[j]
			anagrams = are_anagrams(char_dict, s_inner, substrings_char_dict)
			if anagrams is True:
				num_pairs += 1
	return num_pairs

def are_anagrams(char_dict1, string2, substrings_char_dict):
	len_char_count = sum(char_dict1.values())
	if len_char_count != len(string2):
		return False
	else:
		char_dict2 = get_or_add_chardict(substrings_char_dict, string2)
		return char_dict1.items() == char_dict2.items()

def get_or_add_chardict(substrings_char_dict, string):
	char_dict = dict()
	if string in substrings_char_dict:
		char_dict = substrings_char_dict[string]
	else:
		for c in string:
			if c in char_dict:
				char_dict[c] += 1
			else:
				char_dict[c] = 1
		substrings_char_dict[string] = char_dict
	return char_dict
test_cases = int(input())
for i in range(0, test_cases):
	string = input()
	print(count_anangramic_substring_pairs(string))


from collections import defaultdict
from itertools import combinations

def solve(string):
	anagrams_counter = defaultdict(int)
	for i in range(len(string)):
		for j in range(i, len(string)):
			sorted_str = ''.join(sorted(string[i:j + 1]))
			anagrams_counter[sorted_str] += 1
	num_anagrams = 0
	for (anagram, counter) in anagrams_counter.items():
		num_anagrams += len(list(combinations(range(counter), 2)))
	return num_anagrams
for _ in range(int(input())):
	string = input()
	print(solve(string))


def init(s, start, end, count):
	for i in range(start, end):
		count[ord(s[i]) - ord('a')] += 1
	return count

def compute(s, start, end, count):
	count[ord(s[start - 1]) - ord('a')] -= 1
	count[ord(s[end - 1]) - ord('a')] += 1
	return count
n = int(input())
for i in range(n):
	s = input()
	num_pairs = 0
	for length in range(1, len(s)):
		countx = [0] * 26
		county = [0] * 26
		if init(s, 0, length, countx) == init(s, 1, 1 + length, county):
			num_pairs += 1
		for j in range(2, len(s) - length + 1):
			if countx == compute(s, j, j + length, county):
				num_pairs += 1
		for i in range(1, len(s) - length):
			compute(s, i, i + length, countx)
			county = [0] * 26
			init(s, i + 1, i + 1 + length, county)
			if countx == county:
				num_pairs += 1
			for j in range(i + 2, len(s) - length + 1):
				if countx == compute(s, j, j + length, county):
					num_pairs += 1
	print(num_pairs)


import math

def Combinacao(n, s):
	return math.factorial(n) / (math.factorial(s) * math.factorial(n - s))

def NumeroParesAnagramas(s):
	contador = 0
	for i in range(len(s) - 1):
		(j, inicio, anagramas) = (i, 0, {})
		while j < len(s):
			substring = ''.join(sorted(s[inicio:j + 1]))
			if substring in anagramas:
				anagramas[substring] += 1
			else:
				anagramas[substring] = 1
			inicio += 1
			j += 1
		for substring in anagramas:
			ocorrencias = anagramas[substring]
			if ocorrencias > 1:
				contador += int(Combinacao(ocorrencias, 2))
	return contador
t = int(input())
for i in range(t):
	s = input()
	print(NumeroParesAnagramas(s))


from collections import defaultdict

def anagramic_pairs(string):
	length = len(string)
	count = defaultdict(int)

	def nCr(n, r):
		return n * (n - 1) // 2
	for k in range(1, length):
		for i in range(length - k + 1):
			count[''.join(sorted(string[i:i + k]))] += 1
	return sum((nCr(n, 2) for n in count.values() if n > 1))

def main():
	T = int(input())
	for _ in range(T):
		print(anagramic_pairs(input()))
main()


from collections import Counter
from itertools import combinations
for _ in range(int(input())):
	s = input()
	cnt = 0
	for l in range(1, len(s)):
		r = []
		n = []
		for x in range(len(s) - l + 1):
			t = dict(Counter(s[x:x + l]))
			if t in r:
				n[r.index(t)] += 1
			else:
				r.append(t)
				n.append(1)
		for x in n:
			if x >= 2:
				cnt += len(list(combinations(range(x), 2)))
	print(cnt)


import collections, sys
T = int(sys.stdin.readline())
for _ in range(T):
	S = sys.stdin.readline().strip()
	substrings = (''.join(sorted(S[j:j + i])) for i in range(1, len(S)) for j in range(len(S) - i + 1))
	substrings = collections.Counter(substrings)
	print(sum((v * (v - 1) // 2 for v in substrings.values())))


def anagram(str):
	start = 0
	end = 1
	step = 1
	anagram = []
	anagram_count = []
	anacount = 0
	while step <= len(str):
		while end <= len(str):
			ptr = list(str[start:end])
			ptr.sort()
			count = 0
			for x in anagram:
				if x == ptr:
					if anagram_count[count] == 1:
						anacount += 1
					else:
						anacount += anagram_count[count]
					anagram_count[count] += 1
					break
				count += 1
			else:
				anagram.append(ptr)
				anagram_count.append(1)
			start += 1
			end += 1
		step += 1
		start = 0
		end = step
	return anacount
t = int(input())
while t > 0:
	str = input()
	print(anagram(str))
	t -= 1


from collections import Counter

def find_pairs(s):
	pairs = []
	for i in range(len(s)):
		for j in range(i, len(s) + 1):
			sub = list(s[i:j])
			sub.sort()
			if len(sub) > 0:
				pairs.append(','.join(sub))
	c_pairs = Counter(pairs)
	return sum((c_pairs[i] * (c_pairs[i] - 1) // 2 for i in c_pairs if c_pairs[i] != 1))
t = int(input())
for i in range(t):
	s = input()
	print(find_pairs(s.strip()))


from collections import Counter

def pairs(s):
	length = len(s)
	substrings = []
	for i in range(length):
		for j in range(i, length if i else length - 1):
			substrings.append(''.join(sorted(s[i:j + 1])))
	return sum((sum((i for i in range(cnt))) for cnt in Counter(substrings).values()))
n = int(input())
while n:
	n -= 1
	print(pairs(input()))


from collections import Counter

def arithmetic_sum(x):
	return int(x * (x + 1) / 2)

def get_number_of_anagram_pairs(string):
	count = 0
	substring_size = 1
	string_length = len(string)
	while substring_size < string_length:
		substrings = []
		for i in range(string_length - substring_size + 1):
			substrings.append(''.join(sorted(string[i:i + substring_size])))
		count += sum([arithmetic_sum(x - 1) for x in Counter(substrings).values() if x > 1])
		substring_size += 1
	return count
number_of_cases = int(input())
for _ in range(number_of_cases):
	string = input()
	result = get_number_of_anagram_pairs(string)
	print(result)


def anagram_dict(string):
	return_dict = {}
	for s in string:
		if s in return_dict:
			return_dict[s] += 1
		else:
			return_dict[s] = 1
	return return_dict

def two_strings(string1, string2):
	if anagram_dict(string1) == anagram_dict(string2):
		return True
	else:
		return False

def reduce_string(string):
	if len(string) == 2:
		if string[0] == string[1]:
			return 1
		else:
			return 0
	else:
		slice_range = len(string) - 1
		index = 0
		return_count = 0
		while slice_range > 0:
			if index + slice_range > len(string):
				index = 0
				slice_range -= 1
			else:
				for i in range(index + 1, len(string) - slice_range + 1):
					if two_strings(string[index:slice_range + index], string[i:slice_range + i]):
						return_count += 1
				index += 1
		return return_count
T = int(input())
for _ in range(0, T):
	S = input()
	print(reduce_string(S))


from collections import defaultdict
n = int(input())
for i in range(n):
	w = input()
	x = list(w[:2])
	l = []
	d = defaultdict(list)
	index = 0
	for j in range(len(w)):
		for k in range(j, len(w)):
			l.append(''.join(sorted(w[j:k + 1])))
	s = list(set(l))
	count = []
	for i in range(len(s)):
		count.append(int(l.count(s[i]) * (l.count(s[i]) - 1) / 2))
	print(sum(count))


T = int(input())

def freq_list(inp):
	freq = [0] * 26
	for char in inp:
		freq[char] += 1
	return freq
for i in range(T):
	string = input()
	chars = [ord(c) - 97 for c in string]
	pairs = []
	size = 1
	while size < len(string):
		for n in range(len(chars) + 1 - size):
			pattern = freq_list(chars[n:n + size])
			match = pattern.copy()
			for offset in range(1, len(chars) + 1 - n - size):
				match[chars[n + offset - 1]] -= 1
				match[chars[n + offset + size - 1]] += 1
				if match == pattern:
					pairs += (((n, n + size - 1), (n + offset, n + size + offset - 1)),)
		size += 1
	print(len(pairs))


def process(s):
	cnt = 0
	for sub_len in range(1, len(s)):
		for sub_start in range(0, len(s) - (sub_len - 1)):
			sub = ''.join(sorted(s[sub_start:sub_start + sub_len]))
			for test_start in range(sub_start + 1, len(s) - (sub_len - 1)):
				test = ''.join(sorted(s[test_start:test_start + sub_len]))
				if test == sub:
					cnt += 1
	return cnt
t = int(input())
for _ in range(t):
	print(process(input()))


from pprint import pprint
import sys

def is_substring(t_a, t_b):
	for i in range(26):
		if t_a[i] != t_b[i]:
			return False
	return True

def count_substrings(input):
	count = 0
	lenght = len(input)
	table = [[[0 for i in range(26)] for j in range(lenght)] for k in range(lenght)]
	for p in range(lenght):
		for i in range(p + 1):
			for j in range(p, lenght):
				table[i][j][ord(input[p]) - 97] += 1
	sub_list = set()
	for l in range(1, lenght):
		for i in range(lenght):
			if i + l - 1 > lenght - 1:
				continue
			for j in range(0, lenght):
				if i == j:
					continue
				if j + l - 1 > lenght - 1:
					continue
				result = is_substring(table[i][i + l - 1], table[j][j + l - 1])
				if result == True:
					if i <= j:
						value = (i, i + l - 1, j, j + l - 1)
					else:
						value = (j, j + l - 1, i, i + l - 1)
					sub_list.add(value)
	return len(sub_list)
size = int(sys.stdin.readline())
for i in range(size):
	print(count_substrings(sys.stdin.readline().rstrip()))


import collections, sys
T = int(sys.stdin.readline())
for _ in range(T):
	S = sys.stdin.readline().strip()
	substrings = (''.join(sorted(S[j:j + i])) for i in range(1, len(S)) for j in range(len(S) - i + 1))
	substrings = collections.Counter(substrings)
	print(sum((v * (v - 1) // 2 for v in substrings.values())))


def count_anagram_pairs(s):
	cnt = 0
	for i in range(1, len(s)):
		substrs = {}
		for j in range(len(s) - i + 1):
			ss = ''.join(sorted(list(s[j:j + i])))
			if ss in substrs.keys():
				cnt += substrs[ss]
				substrs[ss] += 1
			else:
				substrs[ss] = 1
	return cnt
t = int(input())
for c in range(t):
	s = input()
	print(count_anagram_pairs(s))


ans = []
for _ in range(0, int(input())):
	sub = []
	let = list(input().strip())
	for l in range(0, len(let)):
		cnt = 1 + l
		while cnt <= len(let):
			if len(let[l:cnt]) == len(let):
				cnt += 1
				continue
			else:
				srt = sorted(let[l:cnt])
				sub.append(''.join(srt))
				cnt += 1
	numSubs = 0
	setLst = list(set(sub))
	for f in range(0, len(setLst)):
		if sub.count(setLst[f]) > 1:
			for x in range(0, sub.count(setLst[f])):
				numSubs += x
	ans.append(numSubs)
for itm in ans:
	print(itm)


cases = int(input())
table1 = [0] * (ord('z') - ord('a') + 1)
table2 = [0] * (ord('z') - ord('a') + 1)

def cleartable(table):
	for i in range(len(table)):
		table[i] = 0

def settable(table, st):
	for i in range(len(st)):
		table[ord(st[i]) - ord('a')] += 1

def inctable(table, c):
	table[ord(c) - ord('a')] += 1

def dectable(table, c):
	table[ord(c) - ord('a')] -= 1

def checktable(table1, table2):
	for i in range(len(table1)):
		if table1[i] != table2[i]:
			return False
	return True

def ana(st1, st2):
	table = [0] * (ord('z') - ord('a') + 1)
	for i in range(len(st1)):
		table[ord(st1[i]) - ord('a')] += 1
	for i in range(len(st2)):
		table[ord(st2[i]) - ord('a')] -= 1
	for i in range(len(table)):
		if table[i] != 0:
			return False
	return True
for i in range(cases):
	st = input()
	count = 0
	for length in range(1, len(st) + 1):
		checked = [[0 for x in range(100)] for x in range(100)]
		for i in range(len(st) - length + 1):
			p = st[i:i + length]
			if i == 0:
				cleartable(table1)
				settable(table1, p)
			else:
				dectable(table1, st[i - 1])
				inctable(table1, st[i + length - 1])
			for j in range(len(st) - length + 1):
				q = st[j:j + length]
				if j == 0:
					cleartable(table2)
					settable(table2, q)
				else:
					dectable(table2, st[j - 1])
					inctable(table2, st[j + length - 1])
				if j == i:
					continue
				if checked[i][j] != 0:
					continue
				if checktable(table1, table2) == True:
					if checked[i][j] == 0:
						checked[i][j] = 1
						checked[j][i] = 1
						count += 1
	print(count)


from collections import defaultdict
cases = int(input())
for _ in range(cases):
	s = input()
	size = len(s)
	anagrams = defaultdict(int)
	for i in range(size):
		histogram = defaultdict(int)
		for j in range(i, size):
			histogram[s[j]] += 1
			anagrams[tuple(sorted(histogram.items()))] += 1
	res = 0
	for (_, count) in anagrams.items():
		res += count * (count - 1) // 2
	print(res)


import math

def anagramCount(s):
	dict = {}
	count = 0
	for i in range(len(s)):
		for j in range(1, len(s) - i + 1):
			cur = [c for c in s[i:i + j]]
			cur.sort()
			key = ''.join(cur)
			dict[key] = dict.get(key, 0) + 1
	for key in dict:
		if dict[key] > 1:
			count += math.factorial(dict[key]) / (math.factorial(2) * math.factorial(dict[key] - 2))
	return int(count)
N = int(input())
for i in range(N):
	s = input()
	num = anagramCount(s)
	print(num)


from collections import defaultdict

def find_res(s):
	(a, res) = (defaultdict(int), 0)
	length = len(s)
	for i in range(length):
		for j in range(i + 1, length + 1):
			a[''.join(sorted(s[i:j]))] += 1
	for i in range(length):
		for j in range(i + 1, length + 1):
			res += a[''.join(sorted(s[i:j]))] - 1
	return res // 2
n = int(input())
for _ in range(n):
	print(find_res(input()))


import sys
count = input()
ins = []
while True:
	try:
		line = input()
	except EOFError:
		break
	ins.append(line)
subStrings = []

def processString(str):
	length = len(str)
	result = []
	table = {}
	for i in range(1, length + 1):
		j = 0
		while j + i < length + 1:
			subStr = ''.join(sorted(str[j:j + i]))
			result.append(subStr)
			if subStr in table:
				table[subStr] += 1
			else:
				table[subStr] = 1
			j += 1
	total = 0
	for key in table.keys():
		total += combinationOfPairs(table[key])
	return total

def combinationOfPairs(n):
	numerator = n * (n - 1)
	return int(numerator / 2)
for str in ins:
	print(processString(str))


from collections import *
for t in range(int(input())):
	check = defaultdict(int)
	s = input()
	l = len(s)
	for i in range(l):
		for j in range(i + 1, l + 1):
			mylist = list(s[i:j])
			mylist.sort()
			mylist = ''.join(mylist)
			check[mylist] += 1
	sum = 0
	for u in check:
		n = check[u]
		sum += n * (n - 1) // 2
	print(sum)


t = int(input())
for i in range(t):
	s = input()
	l = list(s)
	count = 0
	for i in range(0, len(l)):
		for j in range(i, len(l)):
			l1 = sorted(l[i:j + 1])
			for k in range(i + 1, len(l) - len(l1) + 1):
				l2 = sorted(l[k:k + j - i + 1])
				if l1 == l2:
					count += 1
	print(count)


import collections, sys
T = int(sys.stdin.readline())
for _ in range(T):
	S = sys.stdin.readline().strip()
	substrings = (''.join(sorted(S[j:j + i])) for i in range(1, len(S)) for j in range(len(S) - i + 1))
	substrings = collections.Counter(substrings)
	print(sum((v * (v - 1) // 2 for v in substrings.values())))


import math
import sys
import string
import itertools
t = int(input())
while t:
	s = input()
	l = len(s)
	arr = []
	ans = 0
	for i in range(l):
		arr.append([])
		for j in range(l - i):
			arr[i].append(''.join(sorted(s[j:j + i + 1])))
		arr[i].sort()
		k = 0
		cnt = 0
		while k < l - i - 1:
			if arr[i][k] == arr[i][k + 1]:
				k += 1
				cnt += 1
				continue
			ans += int(cnt * (cnt + 1) / 2)
			k += 1
			cnt = 0
		ans += int(cnt * (cnt + 1) / 2)
	print(ans)
	t -= 1


from math import factorial as fac
cal_pairs = lambda n: fac(n) // (fac(n - 2) * fac(2))

def anagram_pairs(s):
	memo = {}
	for i in range(len(s)):
		for j in range(i + 1, len(s) + 1):
			sublist = s[i:j]
			sublist.sort()
			substring = ''.join(sublist)
			if substring in memo.keys():
				memo[substring] += 1
			else:
				memo[substring] = 1
	pairs = 0
	for val in memo.values():
		if val > 1:
			pairs += cal_pairs(val)
	return pairs
t = int(input())
for i in range(t):
	print(anagram_pairs(list(input().strip())))


from collections import defaultdict

def gen_sorted_substrings(s):
	for l in range(1, len(s)):
		for i in range(len(s) - l + 1):
			yield ''.join(sorted(s[i:i + l]))

def get_num_anagram_pairs(s):
	count = defaultdict(int)
	for ss in gen_sorted_substrings(s):
		count[ss] += 1
	return sum((c * (c - 1) // 2 for c in count.values()))
n = int(input())
for _ in range(n):
	s = input()
	print(get_num_anagram_pairs(s))


import collections
T = int(input())
for _ in range(T):
	S = list(input())
	L = len(S)
	total = 0
	for it in range(1, L):
		subs = collections.Counter((str(sorted(S[x:x + it])) for x in range(L - it + 1)))
		for item in subs:
			N = subs[item]
			total += N * (N - 1) // 2
	print(total)


from math import factorial
for _ in range(int(input())):
	word = input()
	words = sorted([''.join(sorted(word[x:x + l])) for x in range(len(word)) for l in range(1, len(word) - x + 1)])
	counts = [words.count(w) for w in set(words)]
	found = int(sum([factorial(c) / (factorial(c - 2) * factorial(2)) for c in counts if c > 1]))
	print(found)


def char_counts(str):
	counts = [0] * 26
	for c in str:
		counts[ord(c) - 97] += 1
	return tuple(counts)
T = int(input())
for _ in range(T):
	line = input()
	N = len(line)
	counts = {}
	for L in range(1, N):
		for i in range(0, N - L + 1):
			j = i + L
			temp = char_counts(line[i:j])
			if temp not in counts:
				counts[temp] = 1
			else:
				counts[temp] += 1
	result = 0
	for (key, value) in counts.items():
		if value > 1:
			result += value * (value - 1) // 2
	print(result)


import sys
import math
num_lines = int(sys.stdin.readline().strip())

def nCr(n, r):
	f = math.factorial
	return f(n) / f(r) / f(n - r)

def s_to_anagram(s):
	letters = dict()
	for c in s:
		count = letters.get(c, 0)
		letters[c] = count + 1
	keys = list(letters.keys())
	keys.sort()
	final_s = ''.join(map(lambda key: key * letters[key], keys))
	return final_s
for _ in range(0, num_lines):
	s = sys.stdin.readline().strip()
	n = len(s)
	anagrams = dict()
	for i in range(0, n):
		for j in range(i + 1, n + 1):
			sub_str = s[i:j]
			anagram = s_to_anagram(sub_str)
			pairs = anagrams.get(anagram, set())
			pairs.add((i, j))
			anagrams[anagram] = pairs
	count = 0
	for (k, v) in anagrams.items():
		c = len(v)
		if c == 1:
			continue
		count += nCr(c, 2)
	print(int(count))


from itertools import combinations

def anagram(a, b):
	for c in set(a):
		if a.count(c) == b.count(c):
			pass
		else:
			return False
	return True
T = int(input())
for _ in range(T):
	S = input()
	length = len(S)
	count = 0
	for i in range(1, length + 1):
		com = combinations(range(length + 1 - i), 2)
		for j in com:
			if anagram(S[j[0]:j[0] + i], S[j[1]:j[1] + i]):
				count += 1
	print(count)


primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311]

def hash(s):
	h = 1
	for c in s:
		h *= primes[ord(c) - ord('a')]
	return h

def run():
	s = input()
	sl = len(s)
	sum = 0
	for l in range(1, sl):
		ana = {}
		for i in range(sl - l + 1):
			h = hash(s[i:i + l])
			if h not in ana:
				ana[h] = 1
			else:
				ana[h] += 1
		for h in ana:
			c = ana[h]
			if c != 1:
				sum += int(c * (c - 1) / 2)
	print(sum)
n = int(input())
for i in range(n):
	run()


def solve(cad):
	cad = list(cad)
	sz = len(cad)
	dic = {}
	tmp = ''
	for i in range(0, sz):
		for j in range(1, sz - i + 1):
			tmp = cad[i:i + j]
			tmp.sort()
			tmp = ''.join(tmp)
			if tmp not in dic:
				dic[tmp] = 1
			else:
				dic[tmp] += 1
	s = 0
	for v in dic.values():
		s += int(v * (v - 1) / 2)
	return s
cant = int(input())
for i in range(cant):
	print(solve(input()))


t = int(input())
for i in range(t):
	x = input()
	x = list(x)
	c = 0
	for j in range(len(x)):
		for k in range(j + 1, len(x)):
			a = x[j:k]
			a.sort()
			for l in range(j, len(x) - (k - j) + 1):
				b = x[l:l + k - j]
				b.sort()
				if a == b:
					c = c + 1
			c -= 1
	print(c)


from collections import defaultdict

class Solution:

	def is_anagram(self, str_1, str_2):
		if len(str_1) != len(str_2):
			return False
		d = defaultdict(int)
		for i in range(len(str_1)):
			d[str_1[i]] += 1
		for i in range(len(str_2)):
			d[str_2[i]] -= 1
		for i in range(len(str_1)):
			if d[str_1[i]] != 0:
				return False
		return True

	def count_anagramic_substrings(self, s):
		count = 0
		for length in range(1, len(s)):
			for i in range(0, len(s) - length):
				test_substr = s[i:i + length]
				for j in range(i + 1, len(s) - length + 1):
					if self.is_anagram(test_substr, s[j:j + length]):
						count += 1
		return count

	def count_anagramic_substrings_2(self, s):
		count = 0
		for length in range(1, len(s)):
			for i in range(0, len(s) - length):
				d = defaultdict(int)
				d_2 = defaultdict(int)
				for j in range(i, i + length):
					d[s[j]] += 1
					d_2[s[j]] += 1
				for j in range(i + 1, len(s) - length + 1):
					d_2[s[j - 1]] -= 1
					if d_2[s[j - 1]] == 0:
						d_2.pop(s[j - 1], None)
					d_2[s[j + length - 1]] += 1
					if d == d_2:
						count += 1
		return count
n = int(input())
strings = []
soln = Solution()
for i in range(n):
	count = 0
	s = str(input())
	strings.append(s)
	count += soln.count_anagramic_substrings_2(s)
	print(count)


from collections import Counter
N = int(input())
for i in range(N):
	s = input()
	ls = len(s) + 1
	found = []
	for j in range(ls):
		for k in range(1, ls - j):
			subs = list(s[j:j + k])
			subs2 = list(subs)
			subs.sort()
			for l in range(1, ls - k - j):
				subs2 = list(s[j + l:j + k + l])
				tmp = list(subs2)
				tmp.sort()
				if subs == tmp:
					found.append(s[j:j + k])
	print(len(found))


cases = int(input())
for caseNo in range(cases):
	s = input()
	n = len(s)
	res = 0
	for l in range(1, n):
		cnt = {}
		for i in range(n - l + 1):
			subs = list(s[i:i + l])
			subs.sort()
			subs = ''.join(subs)
			if subs in cnt:
				cnt[subs] += 1
			else:
				cnt[subs] = 1
			res += cnt[subs] - 1
	print(res)


import collections, sys
T = int(sys.stdin.readline())
for _ in range(T):
	S = sys.stdin.readline().strip()
	substrings = (''.join(sorted(S[j:j + i])) for i in range(1, len(S)) for j in range(len(S) - i + 1))
	substrings = collections.Counter(substrings)
	print(sum((v * (v - 1) // 2 for v in substrings.values())))


def getAllSubstrings(string, length):
	substrings = []
	for i in range(len(string) - length + 1):
		substrings.append(''.join(sorted(string[i:i + length])))
	return substrings

def unorderedAnagramicCount(string):
	buckets = [[] for i in range(100)]
	for i in range(1, len(string)):
		buckets[i - 1] = getAllSubstrings(string, i)
	count = 0
	for i in range(1, len(string)):
		strings = buckets[i - 1]
		for j in range(len(strings)):
			for k in range(j + 1, len(strings)):
				str1 = strings[j]
				str2 = strings[k]
				if str1 == str2:
					count += 1
	return count
T = int(input())
for i in range(T):
	S = input()
	print(unorderedAnagramicCount(S))


def solution(string):
	ans = 0
	unique_keys = {}
	for size in range(1, len(string)):
		counter = 0
		while counter + size <= len(string):
			key = string[counter:counter + size]
			sorted_key = ''.join(sorted(key))
			unique_count = unique_keys.get(sorted_key, 0)
			unique_keys[sorted_key] = unique_count + 1
			counter += 1
	for count in unique_keys.values():
		for i in range(count - 1, 0, -1):
			ans += i
	return ans
T = int(input())
for t in range(T):
	string = input()
	print(solution(string))


import fileinput
input_list = []
for line in fileinput.input():
	input_list.append(line.strip())
T = int(input_list[0])

def ana(s):
	res = 0
	for x in range(len(s) - 1):
		for y in range(x + 1, len(s)):
			for z in range(x + 1, len(s) + 1 + x - y):
				s1 = s[x:y]
				s2 = s[z:y + z - x]
				(lens1, lens2) = (len(s1), len(s2))
				if s1[0] not in s2 or s2[0] not in s1 or s1[lens1 - 1] not in s2 or (s2[lens2 - 1] not in s1) or (s1[int(lens1 * 0.3)] not in s2) or (s2[int(lens2 * 0.7)] not in s1):
					continue
				common = set(s1).intersection(set(s2))
				if lens1 == len(common):
					res += 1
				elif common:
					dupes = 0
					for d in common:
						counts1 = s1.count(d)
						if counts1 == s2.count(d):
							dupes += counts1 - 1
					if lens1 == len(common) + dupes:
						res += 1
	return res
for t in range(1, T + 1):
	s = input_list[t]
	if len(s) < 1:
		res = 0
	else:
		res = ana(s)
	print(res)


norm = ord('a')
for tests in range(int(input())):
	a = input()
	cont = 0
	for i in range(1, 1 + len(a)):
		d = {}
		for j in range(0, len(a) - i + 1):
			s = a[j:i + j]
			s = ''.join(sorted(s))
			if s in d:
				d[s] += 1
			else:
				d[s] = 1
		for j in d:
			n = d[j]
			cont += n * (n - 1) / 2
	print(int(cont))


from collections import defaultdict

def generate_substrings(string):
	substrings = []
	for i in range(len(string)):
		for j in range(i + 1, len(string) + 1):
			substrings.append(string[i:j])
	del substrings[substrings.index(string)]
	return substrings

def factorial(n, end=1):
	if n <= 1:
		return 1
	result = 1
	while n >= end:
		result *= n
		n -= 1
	return result

def choose(n, k):
	return factorial(n, k + 1) // factorial(n - k)
for n in range(int(input())):
	string = input()
	substrings = generate_substrings(string)
	counts = defaultdict(int)
	for substring in substrings:
		counts[''.join(sorted(substring))] += 1
	result = 0
	for (anagram, count) in counts.items():
		if count >= 2:
			result += choose(count, 2)
	print(result)


def getAnagramPair(s):
	l = len(s)
	d = {}
	for length in range(1, l):
		for i in range(0, l - length + 1):
			x = ''.join(sorted(list(s[i:i + length])))
			if x not in d:
				d[x] = 1
			else:
				d[x] += 1
	result = 0
	for k in d:
		result += (d[k] - 1) * d[k] // 2
	return result
T = int(input())
for _ in range(T):
	print(getAnagramPair(input().strip()))


import collections, sys
T = int(sys.stdin.readline())
for _ in range(T):
	S = sys.stdin.readline().strip()
	substrings = (''.join(sorted(S[j:j + i])) for i in range(1, len(S)) for j in range(len(S) - i + 1))
	substrings = collections.Counter(substrings)
	print(sum((v * (v - 1) // 2 for v in substrings.values())))


from collections import defaultdict
N = int(input())
for _ in range(N):
	s = input()
	d = defaultdict(int)
	lst = list(s)
	n = len(lst)
	for i in range(n):
		for l in range(1, n - i + 1):
			sub = lst[i:i + l]
			sub.sort()
			d[''.join(sub)] += 1
	print(sum((v * (v - 1) // 2 for v in d.values())))