hash table
sort
counter
anagram
]
Leetcode 0242. Valid Anagram
https://leetcode.com/problems/valid-anagram
This is very very classical problem and if for some reason interviewer decides to ask it, you response time should be very quick.
First solution is to sort both strings and check if we have the same result. In python it can be done just with one short line. Time complexity is O(n log n)
to perform sort, space depends on which sorting technique we will use, for the following code it is O(n)
.
class Solution:
def isAnagram(self, s, t):
return sorted(s) == sorted(t)
Actually, we do not really need to sort data, we just need to count how many times we have each symbol and there is very useful Counter
function for this. Time complexity is O(n)
, and space is O(m)
, where m
is size of alphabet we are using.
class Solution:
def isAnagram(self, s, t):
return Counter(s) == Counter(t)
If you like the solution, you can upvote it on leetcode discussion section: Problem 0242