Om3ga
Om3ga

Reputation: 32863

How to count anagrams in a string?

I’m trying to solve this question:

Have the function CountingAnagrams take the str parameter and determine how many anagrams exist in the string.

Examples:

Input: "aa aa odg dog gdo" — Output: 2

Input: "a c b c run urn urn" — Output: 1

I tried this solution but it does not display the correct answer. What am I doing wrong?

const CountingAnagrams = (str) => {
  let l = str.length,
    c = 0,
    c1,
    c2;

  if (l % 2 == 0) {
    c1 = str.slice(0, l / 2).split("");
    c2 = str.slice(l / 2).split("");
    
    let l2 = c1.length;

    for (let i = 0; i < l2; i++) {
      let id = c2.indexOf(c1[i]);
      
      if (id !== -1) {
        c2[id] = " ";
      }
      else {
        c += 1;
      }
    }
  }
  else {
    return "-1";
  }
  
  return c;
};

console.log("cars are very cool so are arcs and my os", CountingAnagrams("cars are very cool so are arcs and my os"));
console.log("aa aa odg dog gdo", CountingAnagrams("aa aa odg dog gdo"));
console.log("a c b c run urn urn", CountingAnagrams("a c b c run urn urn"));

Upvotes: 1

Views: 2885

Answers (2)

Deepesh arya
Deepesh arya

Reputation: 17

Sliding Window Solution C++ //(count is stored in ans and anagram positions is in vector v

  vector<int> findAnagrams(string s, string ana) {
 unordered_map<char, int> m;
for(auto it : ana) m[it]++;

int k=ana.length();
int count=m.size();

int i=0, j=0;
int ans=0;
vector<int>v;
while(j<s.length()){

    if(m.find(s[j])!=m.end()){
        m[s[j]]--;
        if(m[s[j]]==0) count--;
    }
    
    if((j-i+1)<k) j++;
    
    else if((j-i+1)==k){

        if(count==0){
            ans++;
            v.push_back(i);
        } 

        if(m.find(s[i])!=m.end()){
            m[s[i]]++;
            if(m[s[i]]==1) count++;
        }

        i++;
        j++;
    }
}
    cout<<ans;
      return v;}

Upvotes: -1

Ankit
Ankit

Reputation: 632

const CountingAnagrams = (str) => {
  // Set() helps to remove all the duplicates
  const wordUnique = new Set(str.split(/\s+/)),
    wordArray = [
      ...wordUnique
    ],
    hash = {};
  let count = 0;
  
  
  wordArray.forEach((word) => {
    // Key will be the sorted word e.g. cba will become abc
    let key = word.split('').sort().join('');
    
    // If there is an anagram they will have the same key so whenever the key is avaialable in the hash count will be updated
    if (key in hash) {
      count += 1;
    }
    else {
      // true is assigned just for making the key available in the hash
      hash[key] = true;
    }
  });
  
  return count;
};

console.log("cars are very cool so are arcs and my os", CountingAnagrams("cars are very cool so are arcs and my os"));
console.log("aa aa odg dog gdo", CountingAnagrams("aa aa odg dog gdo"));
console.log("a c b c run urn urn", CountingAnagrams("a c b c run urn urn"));

Upvotes: 9

Related Questions