Skip to content

Commit d602111

Browse files
authored
Create 2531-make-number-of-distinct-characters-equal.js
1 parent a351131 commit d602111

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* @param {string} word1
3+
* @param {string} word2
4+
* @return {boolean}
5+
*/
6+
const isItPossible = function(word1, word2) {
7+
const map1 = new Array(26).fill(0);
8+
const map2 = new Array(26).fill(0);
9+
10+
const a = 'a'.charCodeAt(0)
11+
// store frequency of characters
12+
for (const ch of word1) map1[ch.charCodeAt(0)-a]++;
13+
for (const ch of word2) map2[ch.charCodeAt(0)-a]++;
14+
15+
for (let i = 0; i < 26; i++) {
16+
if (map1[i] === 0) continue;
17+
for (let j = 0; j < 26; j++) {
18+
if (map2[j] === 0) continue;
19+
20+
// increase freq of char2 and decrease freq of char1 in map1
21+
map1[j]++;
22+
map1[i]--;
23+
24+
// increase freq of char1 and decrease freq of char2 in map2
25+
map2[i]++;
26+
map2[j]--;
27+
28+
// if equal number of unique characters, return true
29+
if (same(map1, map2)) return true;
30+
31+
// revert back changes
32+
map1[j]--;
33+
map1[i]++;
34+
map2[i]--;
35+
map2[j]++;
36+
}
37+
}
38+
39+
return false;
40+
41+
// check if both maps contain equal number of unique characters
42+
function same( map1, map2) {
43+
let count1 = 0;
44+
let count2 = 0;
45+
for (let i = 0; i < 26; i++) {
46+
if (map1[i] > 0) count1++;
47+
if (map2[i] > 0) count2++;
48+
}
49+
50+
return count1 === count2;
51+
}
52+
};
53+

0 commit comments

Comments
 (0)