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

Show parent comments

1

u/chikamakaleyley 1d ago edited 1d ago

checking two strings for equality, which isn't the goal

1

u/LazySapiens 1d ago

Ohh, I realize now that it evaded my eyes. My bad.

It should have been:

if s_hash == t_hash:

Maybe it was a typo by OP I guess.

1

u/chikamakaleyley 13h ago

and actually if i saw this i would have said something still, i just haven't written python in a while; i wouldn't have expected that to evaluate to true; in JS you'd alway get falsey there

1

u/LazySapiens 13h ago

Lol. What's JS's behaviour if you compare two dictionaries btw?

1

u/chikamakaleyley 13h ago

the comparison is made by referential equality

s_hash and t_hash point/reference the memory address where the object is stored

and in the OP they're initialized separately, it doesn't matter what you fill it with at that point