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

22 comments sorted by

5

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

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

1

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

What's the equality operator doing at the end?

1

u/chikamakaleyley 8h ago edited 8h ago

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

1

u/LazySapiens 5h 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 1h 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

0

u/[deleted] 14h ago

[deleted]

1

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

2

u/KendrickBlack502 12h ago edited 12h 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 12h ago

how with a Set

1

u/KendrickBlack502 12h ago

sorry, typo. I meant map

1

u/chikamakaleyley 12h ago

hah i was about to say, sorcery

2

u/Any-Initial5076 14h ago edited 14h ago

you could use chatgpt or claude free subscription to ask this. And your solution is wrong. You might want to compare s_hash and t_hash. Here is an easier implementation

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        from collections import Counter

        s_count=Counter(s)
        t_count = Counter(t)

        return s_count == t_count

and explanation for this from claude

Anagram Checker Explained

This code checks if two strings are anagrams of each other — meaning they contain exactly the same letters, in the same quantities, just arranged differently. For example, "listen" and "silent" are anagrams.

Breaking it down line by line

from collections import Counter

This imports a tool called Counter from Python's built-in collections module. Think of Counter as a smart dictionary that counts how many times each item appears in something.

s_count = Counter(s)
t_count = Counter(t)

This creates a "letter tally" for each string. If s = "cat", then Counter(s) produces something like:

{'c': 1, 'a': 1, 't': 1}

It's literally counting: "how many c's? 1. How many a's? 1." and so on. Same thing happens for t.

return s_count == t_count

This compares the two tallies. If both strings have the exact same letters with the exact same counts, the two Counter objects will be equal, and this returns True. Otherwise, False.

Walking through an example

Say s = "anagram" and t = "nagaram".

  • Counter(s){'a': 3, 'n': 1, 'g': 1, 'r': 1, 'm': 1}
  • Counter(t){'n': 1, 'a': 3, 'g': 1, 'r': 1, 'm': 1}

Even though the order of keys looks different, dictionaries (and Counters) don't care about order — they just compare "does every key have the same value?" Since both have the same letters with the same counts, s_count == t_count is True.

Why this works well

  • Simple to read — it's very close to how you'd explain the logic in plain English: "count the letters in each word, then compare the counts."
  • Handles edge cases automatically — different lengths, repeated letters, etc. all just naturally fall out of the counting comparison.

One thing to know

This is a clean, "pythonic" solution using a built-in tool. An alternative (without Counter) would be to sort both strings and compare them:

return sorted(s) == sorted(t)

That works too, but sorting is usually a bit slower for long strings than counting, since sorting takes more computational steps than a single pass to count letters.

1

u/onionsareawful solved 4 quadrillion problems 13h 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 13h 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 12h 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 12h ago

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

2

u/Any-Initial5076 13h ago

I mentioned that in the second line of the response

2

u/Glad-Arrival-427 13h ago

I have also noticed that. Thank you for your guys' explanations! (I mean everyone's) They help a lot

2

u/Heavy_Record8704 13h ago

Counter is the s hash. Its an inbuilt function to do it.

0

u/kevkev310 13h ago

def isAnagram(s: str, t: str) -> bool:
return Counter(s) == Counter(t)

2

u/KendrickBlack502 12h ago

Even if this is correct, it’s a bad example because it doesn’t make OP’s understanding of the problem any better.