Strings: Making Anagrams

Sort by

recency

|

2151 Discussions

|

  • + 0 comments

    Solution in Ruby:

    def makeAnagram(a, b)
       a_hash = Hash.new(0)
       a.each_char do |c|
          a_hash[c] +=1
       end
       
       del_count = 0
       
       b.each_char do |c|
          if a_hash.key?(c) && a_hash[c]>0
             a_hash[c] -=1
          else
            del_count +=1
          end
       end
       del_count += a_hash.values.sum
       del_count
    end
    
  • + 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
    
  • + 1 comment

    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())