sherlockAndAnagrams HackerRank Solution: Looking for sherlockAndAnagrams solution for Hackerrank problem? Get solution with source code and detailed explainer video.

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 Go to problem statement

## Explanation Video:

Youtube Channel partner: CodingCart

Mentor: Satyendra Jaiswal

Langauge: Python

## Source Code: for `sherlockAndAnagrams`

function

```
# Complete the sherlockAndAnagrams function below.
def sherlockAndAnagrams(s):
count=0
dic=Counter(s)
for i in range(2,len(s)):
sb=s[0:i]
l=len(sb)
dic["".join(sorted(sb))]+=1
for j in range(1,len(s)):
if j+l<=len(s):
dic["".join(sorted(s[j:j+l]))]+=1
# print(dic)
for k,v in dic.items():
count+=v*(v-1)//2
return count
```

coming soon…

coming soon…

## Full Source Code:

```
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the sherlockAndAnagrams function below.
def sherlockAndAnagrams(s):
count=0
dic=Counter(s)
for i in range(2,len(s)):
sb=s[0:i]
l=len(sb)
dic["".join(sorted(sb))]+=1
for j in range(1,len(s)):
if j+l<=len(s):
dic["".join(sorted(s[j:j+l]))]+=1
# print(dic)
for k,v in dic.items():
count+=v*(v-1)//2
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input())
for q_itr in range(q):
s = input()
result = sherlockAndAnagrams(s)
fptr.write(str(result) + '\n')
fptr.close()
```

coming soon…

coming soon…

**Like this article?** Follow us on Facebook and LinkedIn. You can also subscribe to our Youtube Channel.

This post is in partner with CodingCart.