I need to remove common letters from both the strings. But, some of the letters get removed.some of them not. In this example, a is common in both the strings.but not get removed. Could you tell the mistake what I did?
var a = "car"
var b = "karthic"
var c = a.length;
var d = b.length;
for (var i = 0; i < c; i++) {
for (var j = 0; j < d; j++) {
if (a[i] === b[j]) {
a = a.slice(0, i) + a.slice(i + 1);
b = b.slice(0, j) + b.slice(j + 1);
break;
}
}
}
console.log(a + " " + b);
First find all common letters, then remove them from each string:
var a = "car"
var b = "karthic"
var c = a.length;
var d = b.length;
var commonLetters = [];
for (var i = 0; i < c; i++) {
for (var j = 0; j < d; j++) {
if (a[i] === b[j]) {
commonLetters.push(a[i]);
}
}
}
var regex = new RegExp('[' + commonLetters.join('') + ']', 'g')
a = a.replace(regex, '');
b = b.replace(regex, '');
console.log('A: ' + a, 'B: ' + b, commonLetters);
You can convert both strings to a set, find the difference and then filter (include) any characters that are included in the difference.
Access to a Set is O(1) which is better than your (worst-case) O(n^2) loop. You will have to filter all of the characters in each string so this will be O(n) complexity as your base-case.
// Reusable
const strSet = (str) => new Set(str.split(''));
const setDiff = (a, b) => new Set(Array.from(a).filter(item => !b.has(item)));
const prune = (str, set) => str.split('').filter(x => set.has(x)).join('');
// Specific
const a = 'car', b = 'karthic';
const diff = setDiff(strSet(b), strSet(a));
const a1 = prune(a, diff), b1 = prune(b, diff);
console.log(`a1 = "${a1}"\nb1 = "${b1}"`);
let a = "car"
let b = "karthic";
let resultA = a.split('').filter((elem) => b.indexOf(elem) == -1).join('');
let resultB = b.split('').filter((elem) => a.indexOf(elem) == -1).join('');
console.log(resultB);
console.log(resultA);