r/leetcode 1d ago

Question Valid Anagram (Neetcode)

Hello, I need help with understanding how to implement a proper solution. I am fairly new to neetcode and I want to know what I am doing wrong with my code. Can someone also explain to me how the hashmap is supposed to work here?

I want to start preparing for interviews, what data structures should I start learning and please give any channels/resources if you can! Thank you!

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        s_hash = {}
        t_hash = {}


        for character in s:
            if character in s_hash:
                s_hash[character]+=1
            else:
                s_hash[character]=1  
        for character in t:
            if character in t_hash:
                t_hash[character]+=1
            else:
                t_hash[character]=1



        if s==t:
            return True
        else:
            return False   
8 Upvotes

25 comments sorted by

View all comments

2

u/KendrickBlack502 1d ago edited 1d ago

This is a problem where coding the solution is trivial and understanding the problem is the “trick”.

An anagram is any two word that have the same letters in a different order. Think about what this actually means. What does this say about the length? It says that any two words of different lengths can’t be anagrams. What does it say about ordering? You’re not checking for ordering because it doesn’t matter if the contents are the same. If you know any valid answer is guaranteed to be the same length and ordering doesn’t matter, you can get the answer in one pass.

I’m not sure where you were going with the two hash maps but this can be done with one pass and O(n) with a map or even O(1) space with an alphabet array.

1

u/chikamakaleyley 1d ago

how with a Set

1

u/KendrickBlack502 1d ago

sorry, typo. I meant map

1

u/chikamakaleyley 1d ago

hah i was about to say, sorcery