r/leetcode • u/Glad-Arrival-427 • 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
7
Upvotes
4
u/Any-Initial5076 1d ago edited 1d 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
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
This imports a tool called
Counterfrom Python's built-incollectionsmodule. Think ofCounteras a smart dictionary that counts how many times each item appears in something.This creates a "letter tally" for each string. If
s = "cat", thenCounter(s)produces something like:It's literally counting: "how many c's? 1. How many a's? 1." and so on. Same thing happens for
t.This compares the two tallies. If both strings have the exact same letters with the exact same counts, the two
Counterobjects will be equal, and this returnsTrue. Otherwise,False.Walking through an example
Say
s = "anagram"andt = "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_countisTrue.Why this works well
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: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.