Sherlock and Anagrams

Sort by

recency

|

1697 Discussions

|

  • + 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))
        ])
    
  • + 0 comments
    static string sortString(string s) {
            const int MAX_CHAR = 26;
            int[] charCount = new int[MAX_CHAR];
            StringBuilder sb = new StringBuilder();
            
            foreach (char ch in s) {
                charCount[ch - 'a']++;
            }
            
            for (int i = 0; i < MAX_CHAR; i++) {
                for (int j = 0; j < charCount[i]; j++) {
                    sb.Append('a' + i);
                }
            }
            
            return sb.ToString();
        }
        
        static int calculateTotalCombinations(int n){    
            return (n * (n -1)) / 2;
        }
        
        static Dictionary<string, int> findSubstrings(string s) 
        {  
            Dictionary<string, int> dic = new Dictionary<string, int>();
        
            for(int i = 1; i <= s.Length; i++) 
            { 
                for(int j = 0; j <= s.Length - i; j++) 
                {   
                    var substring = sortString(s.Substring(j, i));
                    
                    // Using Substring() function 
                    if(dic.ContainsKey(substring)){
                      dic[substring] = dic[substring] + 1; 
                      continue; 
                    }
                    
                    dic.Add(substring, 1);
                } 
            } 
            
            return dic;
        } 
    
        public static int sherlockAndAnagrams(string s)
        {
            var dic = findSubstrings(s);
            int totalAnagrams = 0;
            
            foreach(var item in dic){
                totalAnagrams+= calculateTotalCombinations(item.Value); 
            }
            
            return totalAnagrams;
        }
    
  • + 0 comments
    import java.io.*;
    import java.math.*;
    import java.security.*;
    import java.text.*;
    import java.util.*;
    import java.util.concurrent.*;
    import java.util.regex.*;
    
    public class Solution {
    
        // Complete the sherlockAndAnagrams function below.
        static int sherlockAndAnagrams(String s) {
            Map<String,Integer> al=new HashMap<>();
            int c=0;
        for(int x=0;x<s.length();x++)
        {
            for(int y=0+x;y<s.length();y++)
            {
                char ar[]=(s.substring(x,y+1)).toCharArray();
                Arrays.sort(ar);
                String q=(String.valueOf(ar));
                Integer o=al.get(q);
                if(o==null)
                {
                    al.put(q,1);
                }
                else
                {
                    al.put(q,o+1);    
                }
            }
        }
            for(String as:al.keySet())
            {
                int ww=al.get(as);
                c+=ww*(ww-1)/2;
            }
        return c;
        }
    
        private static final Scanner scanner = new Scanner(System.in);
    
        public static void main(String[] args) throws IOException {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
    
            int q = scanner.nextInt();
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
    
            for (int qItr = 0; qItr < q; qItr++) {
                String s = (scanner.nextLine());
    
                int result = sherlockAndAnagrams(s);
    
                bufferedWriter.write(String.valueOf(result));
                bufferedWriter.newLine();
            }
    
            bufferedWriter.close();
    
            scanner.close();
        }
    }