Sort by

recency

|

969 Discussions

|

  • + 0 comments

    My c++ solution using map, here is the explanation : https://youtu.be/0-xHzWDVAME

    int anagram(string s) {
        if(s.size() % 2 == 1) return -1;
        map<char, int> mp;
        int ans = 0;
        for(int i = 0; i < s.size() / 2; i++) mp[s[i]]++;
        for(int i = s.size() / 2; i < s.size(); i++){
            if(mp[s[i]] != 0) mp[s[i]]--;
            else ans++;
        }
        return ans;
    }
    
  • + 1 comment

    My Java solution:

    public static int anagram(String s) {
            if (s.length() % 2 != 0) return -1; // If length is odd, return -1
    
            int[] frequency = new int[26]; // Array for character frequencies
    
            int mid = s.length() / 2;
            for (int i = 0; i < mid; i++) {
                frequency[s.charAt(i) - 'a']++;  // Count chars in first half
                frequency[s.charAt(i + mid) - 'a']--; // Subtract chars in second half
            }
    
            int changes = 0;
            for (int count : frequency) {
                if (count > 0) changes += count; // Count excess chars that need replacement
            }
    
            return changes;
        }
    
    • + 1 comment

      this is the most optimized solution i have found so far, thanks for sharing

      • + 0 comments

        of course, im glad it helped you

  • + 0 comments

    Here is my Python solution!

    def anagram(s):
        if len(s) % 2 == 1:
            return -1
        s1 = list(s[:len(s) // 2])
        s2 = list(s[len(s) // 2:])
        letters = set(s1 + s2)
        same = 0
        for letter in letters:
            same += min(s1.count(letter), s2.count(letter))
        return (len(s1) + len(s2) - 2 * same) // 2
    
  • + 0 comments
    simple and fullly
    def anagram(s):
        t=0
        n=len(s)
        if n%2!=0:
            return -1
        a=s[:n//2]
        b=s[n//2:]
        dicta=dict()
        dictb=dict()
        for i in range(n//2):
            if a[i] not in dicta:
                dicta[a[i]]=1
            else:
                dicta[a[i]]+=1
            if b[i] not in dictb:
                dictb[b[i]]=1
            else:
                dictb[b[i]]+=1
        for i in dicta:
           if i in dictb:
            if dicta[i]>=dictb[i]:
                t+=dictb[i]
            else:
                t+=dicta[i]
        t=n//2-t
        return t
    
  • + 0 comments

    Thank you so much for help.