Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common Character Count in Strings JavaScript

Here is the problem:

Given two strings, find the number of common characters between them.

For s1 = "aabcc" and s2 = "adcaa", the output should be 3.

I have written this code :

function commonCharacterCount(s1, s2) {
  var count = 0;
  var str = "";
  for (var i = 0; i < s1.length; i++) {
    if (s2.indexOf(s1[i]) > -1 && str.indexOf(s1[i]) == -1) {
      count++;
      str.concat(s1[i])
    }
  }

  return count;
}

console.log(commonCharacterCount("aabcc", "adcaa"));

It doesn't give the right answer, I wanna know where I am wrong?

like image 899
Nasim Avatar asked Aug 24 '26 18:08

Nasim


2 Answers

There are other more efficient answers, but this answer is easier to understand. This loops through the first string, and checks if the second string contains that value. If it does, count increases and that element from s2 is removed to prevent duplicates.

function commonCharacterCount(s1, s2) {
    var count = 0;
    s1 = Array.from(s1);
    s2 = Array.from(s2);
    
    s1.forEach(e => {
      if (s2.includes(e)) {
        count++;
        s2.splice(s2.indexOf(e), 1);
      }
    });
        
    return count;
}

console.log(commonCharacterCount("aabcc", "adcaa"));
like image 179
Aniket G Avatar answered Aug 26 '26 09:08

Aniket G


You can do that in following steps:

  1. Create a function that return an object. With keys as letters and count as values
  2. Get that count object of your both strings in the main function
  3. Iterate through any of the object using for..in
  4. Check other object have the key of first object.
  5. If it have add the least one to count using Math.min()

let s1 = "aabcc"
let s2 = "adcaa"

function countChars(arr){
  let obj = {};
  arr.forEach(i => obj[i] ? obj[i]++ : obj[i] = 1);
  return obj;
}


function common([...s1],[...s2]){
  s1 = countChars(s1);
  s2 = countChars(s2);
  let count = 0;
  for(let key in s1){
    if(s2[key]) count += Math.min(s1[key],s2[key]);
  }
  return count
}
console.log(common(s1,s2))
like image 29
Maheer Ali Avatar answered Aug 26 '26 09:08

Maheer Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!