242. Valid Anagram

242. Valid Anagram

LeetCode's Valid Anagram problem checks if two strings, `s` and `t`, are anagrams by comparing character frequencies.

YouTube Video

[A1] - Sorting

Time: O(nlog(n))

Space: O(1)

class Solution(object):
    def isAnagram(self, s, t):
        s_sorted = sorted(s)
        t_sorted = sorted(t)

        if s_sorted == t_sorted:
            return True
        else:
            return False
class Solution(object):
    def isAnagram(self, s, t):
        return sorted(s)==sorted(t) # comparing two lists

Comment: In python, string is immutable. That is why here I am using sorted() function instead of sort() as sorted() returns a completely new string and don’t modify the original string.

[A2] - Hash Table

Time: O(n)

Space: O(n)

class Solution(object):
    def isAnagram(self, s, t):
        if len(s)!=len(t):
            return False
        ds, dt= {}, {}
        for i in range(len(s)):
            ds[s[i]] = 1 + ds.get(s[i],0)
            dt[t[i]] = 1 + dt.get(t[i],0)
        for c in ds:
            if ds[c] != dt.get(c,0):
                return False
        return True

Comment: Here we are building our own hash table and checking if the count of all the elements is same.

[A3] - Counter Function

Time: O(n)

Space: O(n)

class Solution(object):
    def isAnagram(self, s, t):
        return Counter(s)==Counter(t)

Comment: This approach works exactly same as A2. We are just using the Counter() function which is handling everything by itself. This approach is probably not suitable for interview.