|
| 1 | +// First Approach - hash map |
| 2 | +var isAnagram = function (s, t) { |
| 3 | + let map = {}; |
| 4 | + for (const char of s) { |
| 5 | + // count character occurence of s |
| 6 | + map[char] ? map[char]++ : (map[char] = 1); |
| 7 | + } |
| 8 | + for (const char of t) { |
| 9 | + // compare character occurence of t to the map object |
| 10 | + if (map[char]) { |
| 11 | + map[char]--; // decrement each time |
| 12 | + } else { |
| 13 | + return false; // if there's a new character, return false |
| 14 | + } |
| 15 | + } |
| 16 | + for (const el of Object.values(map)) { |
| 17 | + // if all the values of the map object is 0, return true |
| 18 | + if (el !== 0) return false; // otherwise return false; |
| 19 | + } |
| 20 | + return true; |
| 21 | +}; |
| 22 | + |
| 23 | +// test cases |
| 24 | +console.log(isAnagram("anagram", "nagarma")); |
| 25 | +console.log(isAnagram("rat", "car")); |
| 26 | + |
| 27 | +// time - O(s + t) - iterate through both input strings |
| 28 | +// space - O(n) - map obj |
| 29 | + |
| 30 | +//Second Approach - sorted strings |
| 31 | +var isAnagram = function (s, t) { |
| 32 | + return s.split("").sort().join("") === t.split("").sort().join(""); |
| 33 | +}; |
| 34 | + |
| 35 | +// test cases |
| 36 | +console.log(isAnagram("anagram", "nagarma")); |
| 37 | +console.log(isAnagram("rat", "car")); |
| 38 | + |
| 39 | +// time - O(nlogn) - using sort method |
| 40 | +// space - O(1) - no extra space memory |
0 commit comments