Sherlock and Anagrams

Sort by

recency

|

1691 Discussions

|

  • + 0 comments

    Perl:

    sub sherlockAndAnagrams {
        my $s = shift;
        my @res;
        my %h;
        my $cnt = 0;
        
        for (my $i = 0; $i < length($s); $i++){
            for (my $j = $i + 1; $j <= length($s); $j++) {
                push(@res, substr($s, $i, $j - $i));
            }
        }
        
        my @sorted = map {join("", sort {$a cmp $b } split("", $_))} @res;
        foreach (@sorted) {
            $h{$_} += 1;
        }
        foreach (values(%h)) {
            $cnt += $_ * ($_ - 1) / 2 if ($_ > 1);
        }
        
        return $cnt;
    }
    
  • + 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);
        }