Valid Anagram - Leetcode 242 - Hashmaps & Sets (Python)

preview_player
Показать описание


Please check my playlists for free DSA problem solutions:

My Favorite Courses:

Data Structures & Algorithms:

Python:

Web Dev / Full Stack:

Cloud Development:

Game Development:

SQL & Data Science:

Machine Learning & AI:
Рекомендации по теме
Комментарии
Автор

Master Data Structures & Algorithms For FREE at AlgoMap.io!

GregHogg
Автор

Another Solution :
def isAnagram(self, s, t):
return sorted(s) == sorted(t)

hamzaunsal
Автор

I used a similar approach to what I did in Ransom Note.
for i in set(s):
if s.count(i) != t.count(i) or len(s) != len(t):
return False
return True

MrIrishBoss
Автор

please do not sort or use Counter, if you are serious about getting a job, this is the same code from the explain but if not the most optimal since we are not checking for unicode values which can be done by using ord()



class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t): # return false if the are not the same length
return False

countS, countT = {}, {}

for index in range(len(s)):
countS[s[index]] = countS.get(s[index], 0) + 1 # get the value if it does not exist set it to 0, else add 1
countT[t[index]] = countT.get(t[index], 0) + 1 # get the value if it does not exist set it to 0, else add 1

return countS == countT # return true or false if the are equal

TheTrackoShow
Автор

Since the anagrams are in lowercase alphabets
So, if we check the frequency of characters with an array of size 26
We iterate through array
One anagram is to count the frequency and the other angaram used to decrease the frequency after that
In the end if we found any element in array Greater thank 0 return false otherwise return true
This approach also works in O(n) time complexity and with constant space complexity

dileepkonchada
Автор

Is the time complexity really O(n)? I ask it because the Counter need run through list to creat the dictionary and sort the last one.

CharlyBraga
Автор

nice short solution, thanks for sharing

christianjt
Автор

Do you recommend using Counter in an actual interview?

helloworldcsofficial
Автор

This is an awesome series keep it up 👍🏾

jorgesanabria
Автор

With all due respect, this is a horrible solution for a coding interview. Never import during leetcode interview. They dont want you taking the easy way out

RealDarkFilm
welcome to shbcf.ru