Strings: Making Anagrams

Sort by

recency

|

2150 Discussions

|

  • + 0 comments

    Intuitive, Readable Python code: O(N) complexity.

    def makeAnagram(a, b):
        # Write your code here
        a_list = list(a)
        b_list = list(b)
        remove_b = 0
        for l in b_list: 
            if l in a_list: 
                a_list.remove(l)
            else:
                remove_b +=1 
        remove_a = len(a_list) # unmatched letters remained in this list
        return remove_a + remove_b
    
  • + 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())
    
  • + 1 comment

    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)