We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
fromcollectionsimportdefaultdictdefsherlockAndAnagrams(s):n=len(s)anagram_count=0substring_map=defaultdict(int)# Iterate over all possible substringsforlengthinrange(1,n):# Generate all substrings of current lengthforstartinrange(n-length+1):substr=''.join(sorted(s[start:start+length]))substring_map[substr]+=1# Count anagrammatic pairsforcountinsubstring_map.values():anagram_count+=count*(count-1)// 2returnanagram_countif__name__=='__main__':q=int(input().strip())for_inrange(q):s=input().strip()result=sherlockAndAnagrams(s)print(result)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sherlock and Anagrams
You are viewing a single comment's thread. Return to all comments →
My Python Solution