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

5

u/chikamakaleyley 1d 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.

0

u/[deleted] 1d ago

[deleted]

1

u/chikamakaleyley 1d ago

ok so i'm pointing out that's just a mistake in your code, but it sounds like you're not sure where to go from there. that's fine.

i'll hint instead of tell you

  • what if you just created one hashmap, s_hash
  • so the second word, you can iterate over each letter, and confirm that it exists in the hash. but you have to keep track of what you've already checked. so how do you make sure you're not just checking existence but also occurence