-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisAnagram.js
More file actions
executable file
·47 lines (25 loc) · 899 Bytes
/
isAnagram.js
File metadata and controls
executable file
·47 lines (25 loc) · 899 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// function to check if two strings are anagrams
// what is anagram ?
// two strings are anagrams if they contain same characters with same frequency
// example :
// "listen" and "silent" are anagrams
// "triangle" and "integral" are anagrams
// "apple" and "pale" are not anagrams
function isAnagram(str1, str2) {
if(str1.length !== str2.length) return false;
let map = {};
for(let ch of str1) {
map[ch] = (map[ch] || 0) + 1;
}
for(let ch of str2) {
if(!map[ch]) return false;
map[ch]--;
}
return true;
}
// test the function
console.log(isAnagram("listen", "silent")); // Output: true
console.log(isAnagram("triangle", "integral")); // Output: true
console.log(isAnagram("apple", "pale")); // Output: false
console.log(isAnagram("anagram", "nagaram")); // Output: true
console.log(isAnagram("rat", "car")); // Output: false