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):defget_frequency_hash(freq):returntuple(freq)n=len(s)anagram_count=0freq_map=defaultdict(int)# Calculate cumulative frequency for each positioncum_freq=[[0]*26for_inrange(n+1)]foriinrange(1,n+1):cum_freq[i]=cum_freq[i-1][:]cum_freq[i][ord(s[i-1])-ord('a')]+=1# Count frequency differencesforlengthinrange(1,n):freq_map.clear()foriinrange(n-length+1):j=i+lengthfreq_diff=[cum_freq[j][k]-cum_freq[i][k]forkinrange(26)]freq_hash=get_frequency_hash(freq_diff)freq_map[freq_hash]+=1# Calculate anagram pairsforcountinfreq_map.values():anagram_count+=count*(count-1)// 2returnanagram_count
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 →