Created
November 6, 2024 03:37
-
-
Save sAVItar02/23c0d533e6fd366110c013157dc3c8cc to your computer and use it in GitHub Desktop.
Valid Anagram
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} s | |
* @param {string} t | |
* @return {boolean} | |
*/ | |
var isAnagram = function(s, t) { | |
if(s.length != t.length) return false; | |
let dict = {}; | |
for(let i=0; i<s.length; i++) { | |
if(dict[s[i]]) dict[s[i]] += 1; | |
else dict[s[i]] = 1; | |
} | |
for(let i=0; i<t.length; i++) { | |
if(dict[t[i]] != 0) dict[t[i]] -= 1; | |
if(dict[t[i]] == 0) delete dict[t[i]]; | |
} | |
if(Object.keys(dict).length === 0) return true; | |
return false; | |
}; | |
// Maintain a dictionary | |
// go through the first string and add all the characters in the array, if multiple occurences then increase the count | |
// go through the second string and reduce the count of all, if the count is 0 then remove from dictionary | |
// at the end, if the dict is empty then return true, else return false | |
// Time: O(n) | |
// Space: O(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment