Sherlock and Anagrams

Sort by

recency

|

1690 Discussions

|

  • + 0 comments

    C#

    public static int sherlockAndAnagrams(string s)
    {
        var anagrams = 0;
        var frequency = new Dictionary<string, int>();
    
        for (int i = 0; i < s.Length; i++)
        {
            for (int j = i + 1; j <= s.Length; j++)
            {
                var sub = new string(s.Substring(i, j - i).OrderBy(s => s).ToArray());
    
                if (frequency.ContainsKey(sub))
                    frequency[sub]++;
                else
                    frequency[sub] = 1;
            }
        }
    
        foreach (var (key, value) in frequency)
            anagrams += value * (value - 1) / 2;
    
        return anagrams;
    }
    
  • + 0 comments

    C#

    public static int sherlockAndAnagrams(string s)
    {
        var anagrams = 0;
        var windows = s.Length - 1;
    
        for (int w = 1; w <= windows; w++)
        {
            for (int i = 0; i <= s.Length - w - 1; i++)
            {
                for (int j = i + 1; j <= s.Length - w; j++)
                {
                    var str1 = s.Substring(i, w);
                    var str2 = s.Substring(j, w);
    
                    var sortedStr1 = new string(str1.OrderBy(c => c).ToArray());
                    var sortedStr2 = new string(str2.OrderBy(c => c).ToArray());
    
                    if (sortedStr1 == sortedStr2)
                    {
                        anagrams++;
                    }
                }
            }
        }
    
        return 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
    
  • + 0 comments

    Java 8

    My solution :

     public static int sherlockAndAnagrams(String s) {
        
           Map<String,Integer> matchMap = new HashMap<>();
          
           for(int i= 0; i < s.length(); i++){
               for(int j= i+1; j <= s.length(); j++){
                    char[] array = s.substring(i, j).toCharArray();
                    Arrays.sort(array);
                    String orderSubString = String.valueOf(array);
                    matchMap.compute(orderSubString, (k,v) -> (v != null ? v : 0) + 1); 
               }
           }
           
           matchMap.replaceAll((k, v) -> IntStream.range(1, v).sum());
           return matchMap.values().stream().reduce(0, (a,b)-> a+b);
        }
    
  • + 0 comments

    C++

    My solution using combinations.

    int get_two_combination(int substr_count)
    {
        if(substr_count < 2)
        {
            return 0;
        }
        return substr_count * (substr_count-1) / 2;
    }
    
    int sherlockAndAnagrams(string s) 
    {
        map<string, int> anagrams;
        int pair_count = 0;
        for(int i = 1; i < s.size(); i++)
        {
            for(int j = 0; (j + i) <= s.size(); j++)
            {
                string cur_substr = s.substr(j, i);
                sort(cur_substr.begin(), cur_substr.end());
                anagrams[cur_substr]++;
                cout << cur_substr << endl;
            }
        }
        
        for(auto it = anagrams.begin(); it != anagrams.end(); it++)
        {
            pair_count += get_two_combination(it->second);
        }
        return pair_count;
    }