Sherlock and Anagrams

Sort by

recency

|

1700 Discussions

|

  • + 0 comments

    import java.io.; import java.util.;

    class Result {

    /*
     * Complete the 'sherlockAndAnagrams' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts STRING s as parameter.
     */
    
    public static int sherlockAndAnagrams(String s) {
        Map<String, Integer> freqMap = new HashMap<>();
        int n = s.length();
    
        // Generate all substrings
        for (int i = 0; i < n; i++) {
            int[] count = new int[26];
            for (int j = i; j < n; j++) {
                count[s.charAt(j) - 'a']++;
                StringBuilder key = new StringBuilder();
                for (int k = 0; k < 26; k++) {
                    key.append(count[k]).append('#');
                }
                String signature = key.toString();
                freqMap.put(signature, freqMap.getOrDefault(signature, 0) + 1);
            }
        }
    
        int totalPairs = 0;
        for (int val : freqMap.values()) {
            totalPairs += (val * (val - 1)) / 2;
        }
    
        return totalPairs;
    }
    

    }

    public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int q = Integer.parseInt(bufferedReader.readLine().trim());
    
        for (int qItr = 0; qItr < q; qItr++) {
            String s = bufferedReader.readLine();
            int result = Result.sherlockAndAnagrams(s);
            bufferedWriter.write(String.valueOf(result));
            bufferedWriter.newLine();
        }
    
        bufferedReader.close();
        bufferedWriter.close();
    }
    

    }

  • + 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