LeetCode: Valid Anagram
This solution is pretty simple and compact. It’s a solid answer, but not the most creative one. I knew I could come to a solution using an object, creating an object with keys of the characters in one string, and values of the number of times that character occurs in the string. First I’d create an empty object, the loop I’d use to populate this object is a pretty standard format.
Before going further, I want to account for a fringe case that will result in a false return. If the strings are different lengths, it’s impossible for the two to be anagrams of each other. I want to check this before looping and populating the object, so I’ll do that at the top of the function.
After the object is created I’m going to loop through the next string to check each key in the object. To start, if the current character in the string doesn’t exist as a key, then the function will end and return false. When the character does exist as a key, I want to reduce that value by 1. If the value is reduced and the key’s current value is 0, then I’ll delete that key from the object. If an object is an anagram, then at the end of the loop the object will be empty again.
Finally, at the end, I want the function to return true if the object ends up being empty. Since the function uses two loops next to each other, instead of two nested loops, the function’s Big O Time Complexity ends up being O(2n), or simplified to O(n) since both have the same growth rate.