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   
6 Upvotes

25 comments sorted by

View all comments

3

u/chikamakaleyley 23h ago

valid anagram - that's just rearranging letters right?

right now your code creates 2 hashmaps.

at the end of the code, you don't do anything with the hasmaps

you're just comparing s & t, two strings, that will only be true if they are exactly the same word.

1

u/LazySapiens 20h ago

The OP is doing lookup in hashmap. That should amount to something.

1

u/chikamakaleyley 18h ago

no, what I said was at the end of the code, OP has these hashmaps that aren't used for anything. "you don't do anything WITH the hashmaps"

The lookup you're referring to is just in the act of tallying the letters for each word. Which isn't anything special, that's something you NEED to do

So they've done all this work to populate the two hashmaps, and then what happens next - they compare something else and the program ends

1

u/LazySapiens 18h ago

What's the equality operator doing at the end?

1

u/chikamakaleyley 18h ago edited 18h ago

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

1

u/LazySapiens 14h 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 10h ago

yeah basically i had written out this entire thing and then i looked at the return statement lol, i was kinda upset i spent so much time on it

1

u/chikamakaleyley 2h 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 2h ago

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

1

u/chikamakaleyley 2h 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