In this Sherlock and Anagrams HackerRank solution, 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
The list of all anagrammatic pairs is at positions 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
Input Format
The first line contains an integer , the number of queries.
Each of the next lines contains a string to analyze.
Constraints
contains only lowercase letters in the range ascii[a-z].
Sherlock and Anagrams HackerRank solution
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in C#
public static int sherlockAndAnagrams(string s)
{
List<string> substrings = new();
int count = 0;
for (int i = 1; i < s.Length; i++) {
for (int j = 0; j <= s.Length - i; j++) {
string substring = sortString(s.Substring(j, i));
count += substrings.FindAll(str => str == substring).Count;
substrings.Add(substring);
}
}
return count;
}
public static string sortString(string s) {
List<char> chars = s.ToCharArray().ToList();
chars.Sort();
return new string(chars.ToArray());
}
Problem Solution in Python
def sherlockAndAnagrams(s : str) -> int:
hashmap = {}
count = 0
for i in range(1,len(s) + 1):
for j in range(len(s) - i + 1):
substring = str(''.join(sorted(s[j : j + i])))
if substring in hashmap:
count += hashmap[substring]
hashmap[substring] += 1
else:
hashmap[substring] = 1
return count
Problem Solution in JavaScript
function sherlockAndAnagrams(s) {
let count = 0;
let map = new Map();
for(let i = 0; i < s.length; i++){
for(let j = i + 1; j <= s.length; j++){
let substring = s.substring(i,j).split('').sort().join('');
if(map.has(substring)){
count += map.get(substring);
map.set(substring, map.get(substring) + 1);
} else{
map.set(substring, 1);
}
}
}
return count;
}
Leave a Reply