DEV Community

David Babalola
David Babalola

Posted on

LeetCode DSA Series #5: 242. Valid Anagram

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

You can find the problem here.

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

        if len(s) != len(t):
            return False
        for k, v in counts_t.items():
            if v != counts_s[k]:
                return False
        return True
Enter fullscreen mode Exit fullscreen mode

For this problem, I used the Counter class from collections.
The final time and space complexity are O(n)

Top comments (0)