Sort by

recency

|

978 Discussions

|

  • + 0 comments

    Here is solution in python, java, c++, c and javascript - https://programmingoneonone.com/hackerrank-anagram-problem-solution.html

  • + 0 comments

    int anagram(string s) {

    if(s.size() % 2 != 0) return -1;
    
    string left = s.substr(0 , s.size()/2);
    string right = s.substr(s.size()/2);
    
    int freq[26] = {0};
    
    for(char c : left) freq[c - 'a']++;
    for(char c : right) freq[c - 'a']--;
    
    int changes = 0;
    
    for(int i = 0; i < 26 ; i++){
        if(freq[i] > 0) changes += freq[i];
    }
     return changes;
    

    }

  • + 0 comments

    include

    include

    using namespace std;

    /*Think of it this way: e.g.xaxb|bbxx left : 2x 1a 1b right: 2x 0a 2b , and they cancle out. What is left in the right is the answer.

    O(n) per query*/

    int arr[26];

    int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);

    int q;
    cin >> q; 
    
    string str; 
    while(q--) {
        cin >> str; 
        if(str.size() % 2) { cout << -1 << '\n'; continue; }
    
        int mid = str.size() >> 1; 
    
        for(int i = 0; i < mid; ++i) ++arr[str[i] - 'a']; 
    
        int ret = 0; 
        for(int i = mid; i < str.size(); ++i) {
            if(arr[str[i] - 'a']) --arr[str[i] - 'a']; 
            else ++ret; 
        }
    
        cout << ret << '\n'; 
        memset(arr, 0, sizeof(arr)); 
    }
    
    return 0; 
    

    }

  • + 0 comments

    Minimalist O(n) solution:

        public static int anagram(String s) {
            if (s.length() % 2 != 0) return -1;
            
            int size = s.length() / 2;
            int[] s1 = new int[26];
            int base = 'a';
            int changes = 0;        
    
            //build first half
            for (int i = 0; i < size; i++) {
                s1[s.charAt(i) - base] ++;
            }
    
            //check second half
            for (int i = size; i < size*2; i++) {
                if (s1[s.charAt(i) - base] > 0) s1[s.charAt(i) - base]--;
                else changes++;
            }
    
            return changes;
        
        }
    
  • + 0 comments
    # Anagram
    from collections import Counter
    def anagram(s):
        len_s = len(s)
        result = -1
        if len_s % 2 == 0:
            l, r = Counter(s[:len_s // 2]), Counter(s[len_s // 2:])
            result = sum((r - l).values())
        return result