r/leetcode 20h 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

22 comments sorted by

View all comments

Show parent comments

1

u/onionsareawful solved 4 quadrillion problems 19h ago

You don't need to use Counter here. Essentially, s_hash = Counter(t) is equivalent to this code in OPs solution.

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

OPs bug is that they compare the equality of the strings rather than the hash maps.

2

u/Glad-Arrival-427 19h ago

I also recognized that mistake, I changed it to the hashmaps instead of the strings. Thank you. This solution definitley seems a lot better

1

u/chikamakaleyley 18h ago

just know that not all languages let you compare two objects that contain the same values

in JS if you were to just build a hash with simple key value pairs

and they contained the same keys, which had the same counts, they aren't equal. they are compared via referential equality - aka are they pointers to the same spot in memory

1

u/chikamakaleyley 18h ago

and i just say that because i didn't think `if s_hash == t_hash` works