Strings: Making Anagrams

Sort by

recency

|

2149 Discussions

|

  • + 0 comments

    Python solution using one dictionary to count all the letters in the first string, remove all the letters in the second string, and them summing up the absolute counts of each letter for the answer.

    def makeAnagram(a, b):
        letters = {}
        for _ in a: letters[_] = letters.get(_, 0) + 1
        for _ in b: letters[_] = letters.get(_, 0) - 1
        return sum(map(abs, letters.values()))
    
  • + 0 comments

    Here is simple C# code, that does the trick. Here I am deleting characters thats are found from both the strings (1 character each). We will be left with characters that are now found in both.

    public static int makeAnagram(string a, string b) { string sS1 = ""; string sS2 = "";

        if(a.Length > b.Length)
        {
            sS1 = a;
            sS2 = b;
        }
        else
        {
            sS1 = b;
            sS2 = a;
        }
    
        for(int i = 0; i < sS1.Length; i++)
        {
            for(int j = 0; j < sS2.Length; j++)
            {
                if(sS1[i] == sS2[j])
                {
                    sS1 = sS1.Remove(i,1);
                    sS2 = sS2.Remove(j,1);
                    i--;
                    j--;
                    break;
                }
            }
            continue;
        }
    
        return sS1.Length + sS2.Length;
    
    
    }
    
  • + 0 comments
    def makeAnagram(a, b) -> int:
        # Write your code here
        ca, cb = Counter(a), Counter(b)
        diff = (ca|cb) - (ca&cb)
        return sum(diff.values())
    
  • + 0 comments

    Python solution

    def makeAnagram(a, b):
        counter_a = Counter(a)
        counter_b = Counter(b)
        unique_char = set(a).union(set(b))
        
        return sum(abs(counter_a[char] - counter_b[char]) for char in unique_char)
    
  • + 0 comments
                char[] aArray = a.ToCharArray();
                char[] bArray = b.ToCharArray();  
                Array.Sort(aArray);
                Array.Sort(bArray);  
                int i = 0, j = 0;
                int count = 0;
                while (i < aArray.Length && j < bArray.Length)
                {
                     if (aArray[i] == bArray[j])
                     {
                            i++;
                            j++;
                     }
                     else if (aArray[i] < bArray[j])
                     {
                            i++;
                            count++;
                     }
                    else
                 {
                         j++;
                         count++;
                 }
            }
            if(i < aArray.Length)
            {
                 count += aArray.Length - i;
            }
            if(j < bArray.Length)
            {
                 count += bArray.Length - j;
            }
    
            return count;