Make Number of Distinct Characters Equal - Try Each Pair of Characters [JS]
Solution: Try Each Pair of Characters
- Count the occurances of each character in
word1
andword2
. - Try each pair of characters (
26 * 26
).
We can figure out the number of distinct characters inword1
andword2
after we swap characteri
fromword1
with characterj
fromword2
.- New distinct character count in
word1
:- If character
j
does not exist inword1
,+1
- If character
i
has only one occurance inword1
,-1
- If character
- New distinct character count in
word2
:- If character
i
does not exist inword2
,+1
- If character
j
has only one occurance inword2
,-1
- If character
- Note: When
i
andj
are equal, we return true if the original distinct character counts are equal.
- New distinct character count in
n = length of word1
,m = length of word2
Time Complexity: O(n + m + 26*26)
Space Complexity: O(1)
var isItPossible = function(word1, word2) {
let count1 = Array(26).fill(0), distinctCount1 = 0;
let count2 = Array(26).fill(0), distinctCount2 = 0;
for (let i = 0; i < word1.length; i++) {
count1[word1.charCodeAt(i) - 97]++;
if (count1[word1.charCodeAt(i) - 97] === 1) distinctCount1++;
}
for (let i = 0; i < word2.length; i++) {
count2[word2.charCodeAt(i) - 97]++;
if (count2[word2.charCodeAt(i) - 97] === 1) distinctCount2++;
}
for (let i = 0; i < 26; i++) {
for (let j = 0; j < 26; j++) {
if (count1[i] === 0 || count2[j] === 0) continue;
if (i === j) {
if (distinctCount1 === distinctCount2) return true;
continue;
}
let newCount1 = distinctCount1 + (count1[j] === 0 ? 1 : 0) + (count1[i] === 1 ? -1 : 0);
let newCount2 = distinctCount2 + (count2[i] === 0 ? 1 : 0) + (count2[j] === 1 ? -1 : 0);
if (newCount1 === newCount2) return true;
}
}
return false;
};
Comments
Post a Comment