Sherlock and Anagrams

  • + 0 comments

    Its not exactly a fast solution but I used this same idea. Here is my python code for it. First I generate a dictionary with a k,v pair which is (length of substring, substrings of the same length). Then I generate all the possible substrings and for each one I sort them and them find out if the sorted substring is already in the array of sorted substrings of the same length. If so we've found another anagram so we increment the anagram counter. After generating all the substrings we will also have the number of anagrams.

    def sherlockAndAnagrams(s):
        anagrams = 0
        substrings = {i: [] for i in range(1, len(s) + 1)}
        for i in range(0, len(s)):
            for j in range(i+1, len(s) + 1):
                substr = " ".join(sorted(s[i:j]))
                for k in range(0, len(substrings[j-i])):
                    if substrings[j-i][k] == substr:
                        anagrams += 1
                substrings[j-i].append(substr)
        return anagrams