Sherlock and Anagrams

  • + 0 comments

    O(n^2) solution python
    quadratic solution python

    def sherlockAndAnagrams(s):
        count = 0
    
        for window_size in range(1, len(s)):
    
            counter = _count(s[:window_size])
            snapshots = collections.defaultdict(lambda: 0)
            snapshot = tuple(counter.values())
            snapshots[snapshot] += 1
    
            for i in range(1, len(s) - window_size + 1):
                j = i + window_size - 1
                counter[s[i-1]] -= 1
                counter[s[j]] += 1
    
                snapshot = tuple(counter.values())
                count += snapshots[snapshot]
                snapshots[snapshot] += 1
    
        return count
    
    def _count(s: str) -> dict[str, int]:
        counter = dict.fromkeys("abcdefghijklmnopqrstuvwxyz", 0)
        for char in s:
            counter[char] += 1
        return counte