Making Anagrams

Sort by

recency

|

763 Discussions

|

  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/B4pZbX0VzzU

    #include <bits/stdc++.h>
    
    using namespace std;
    
    int main()
    {
        string fstr, sstr;
        cin >> fstr; cin >> sstr;
        vector<int>fsc(26,0), ssc(26,0);
        int i, result = 0;
        for(i = 0; i < fstr.size(); i++) fsc[fstr[i] - 'a']++;
        for(i = 0; i < sstr.size(); i++) ssc[sstr[i] - 'a']++;
        for(i = 0; i < 26; i++) result += abs(fsc[i] - ssc[i]);
        cout << result << endl;
        return 0;
    }
    
  • + 0 comments

    int makingAnagrams(string s1, string s2) { unordered_map f1,f2;

      for(int i=0;i<s1.length();i++){
           f1[s1[i]]++; }
    
      for(int i=0;i<s2.length();i++){
           f2[s2[i]]++;}
    
      int ans=0 ;
      for(char i ='a';i<='z';i++){
        ans+= abs(f1[i]-f2[i]);  
      }
    return ans;
    

    }

  • + 0 comments

    Here is my Python solution!

    def makingAnagrams(s1, s2):
        same = 0
        letters = set(list(s1) + list(s2))
        for letter in letters:
            print(list(s1).count(letter), list(s2).count(letter), letter)
            same += min(list(s1).count(letter), list(s2).count(letter))
        return len(s1) + len(s2) - 2 * same
    
  • + 0 comments

    Perl:

    sub makingAnagrams {
        my $s1 = shift;
        my $s2 = shift;
        my (%h1, %h2);
        my $cnt = 0;
        my $sum = 0;
        
        foreach (split("", $s1)) {
            $h1{$_} += 1;
        }
        foreach (split("", $s2)) {
            $h2{$_} += 1;
        }
        foreach my $k (keys %h1) {
            if (exists($h2{$k})) {
                $cnt += abs($h1{$k} - $h2{$k});
                delete $h1{$k};
                delete $h2{$k};
            }
            else {
                $cnt += $h1{$k};
                delete $h1{$k};
            }        
        }
        foreach my $k2 (keys %h2) {
            $sum += $h2{$k2};
        }
        return $cnt + $sum;
    }
    
  • + 0 comments

    My answer with Typescript, simple

    function makingAnagrams(s1: string, s2: string): number {
        // 0. define hash [m]
        let m = new Map<string, number>()
    
        // 1. counting [c]+ in [s1]
        // 2. counting [c]- in [s2]
        for (let c of s1) m.set(c, (m.get(c) || 0) + 1)
        for (let c of s2) m.set(c, (m.get(c) || 0) - 1)
    
        // 3. return sum of diff of each character between [s1]&[s2] that counted in [m]
        return Array.from(m.values()).reduce((p, c) => p + Math.abs(c), 0)
    }