EasyNo. 0242

Valid Anagram — LeetCode 242 Python Solution

Pattern
Sorting
Topics
Hash Table, String, Sorting
Reading time
2 min

The problem

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

Python solution

PythonSolution
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        cnt = Counter(s)
        for c in t:
            cnt[c] -= 1
            if cnt[c] < 0:
                return False
        return True

Complexity

Time
O(n), the space complexity is O(C), where n is the length of the string; and C is the size of the character set, which is C=26 in this problem
Space · auxiliary
O(C), where n is the length of the string; and C is the size of the character set, which is C=26 in this problem

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 242. Valid Anagram is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0049Group AnagramsMedium
0389Find the DifferenceEasy
0451Sort Characters By FrequencyMedium
0522Longest Uncommon Subsequence IIMedium
0692Top K Frequent WordsMedium
0720Longest Word in DictionaryMedium

Frequently asked questions

How hard is LeetCode 242. Valid Anagram?

LeetCode 242. Valid Anagram is rated Easy on LeetCode.

What is the time complexity of LeetCode 242. Valid Anagram?

The Python solution on this page runs in O(n), the space complexity is O(C), where n is the length of the string; and C is the size of the character set, which is C=26 in this problem.

What is the space complexity of LeetCode 242. Valid Anagram?

The Python solution on this page uses O(C), where n is the length of the string; and C is the size of the character set, which is C=26 in this problem auxiliary space.

What topics does LeetCode 242. Valid Anagram cover?

LeetCode 242. Valid Anagram is tagged Hash Table, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.