Sherlock and Anagrams

Sort by

recency

|

1699 Discussions

|

  • + 0 comments

    Ruby solution:

    def sherlockAndAnagrams(s)
        substrings = Hash.new { |h,k| h[k] = 0 }
        (0..s.length - 1).each do |i|
            (i..s.length - 1).each do |j|
                sorted = s[i..j].chars.sort.join
                substrings[sorted] += 1
            end
        end
            
        substrings.values.
            filter { |f| f > 1 }.
            map { |k| k * (k - 1) / 2 }.
            sum
    end
    
  • + 0 comments

    A short CPP version:

    int sherlockAndAnagrams(std::string s) {
        std::map<std::map<char,int>, int> unique_strings;
        int result = 0;
        for (size_t i = 0; i<s.size(); ++i){
            std::map<char,int> submap;
            for (size_t j = i; j<s.size(); ++j) {
                submap[s[j]]++;
                unique_strings[submap]++;
            }
        }
        for (auto& [substr, count]: unique_strings) {
            result += (count - 1)* count / 2;
        }
        return result;
    }
    
  • + 0 comments

    Here's the approch that I implement to solve this problem with Kotlin:

    fun sherlockAndAnagrams(s: String): Int {
        var windowedSize = s.length - 1 // define possible windowed steps for that string
        var listOfWindows : List<List<Char>> = listOf()
        var anagramsCounter = 0
        
        // itterate based on possible windowed steps
        while(windowedSize > 0){
            // get all windowed sets
            listOfWindows = s.toList().windowed(size = windowedSize, step = 1) { it ->
                it.sortedBy { it }
            }
            // count all anagrams
            listOfWindows.forEachIndexed{ index, window ->
                for(j in (index + 1) .. listOfWindows.lastIndex) {
                    if(window == listOfWindows[j])  
                        anagramsCounter++
                }
            }
            windowedSize-- // reduce the windowed size
        }
        return anagramsCounter
    }
    
  • + 0 comments

    I wanted to use the NCR formula to count permutations, which uses factorials.

    100! is a very big number. (9e157)

    Luckily c# has the arbitrary System.Numerics.BigInteger

  • + 0 comments

    python (NOTE replace '@' with ':' - HackerRank didn't allow to upload this comment when having ':' in the text).

    import itertools
    def sherlockAndAnagrams(s):
        return sum([
        len([
            pair
            for pair in itertools.combinations([s[i@i+l] for i in range(len(s) - l + 1)], 2)
            if sorted(pair[0]) == sorted(pair[1])
        ])
        for l in range(1, len(s))
        ])