Valid Anagram — LeetCode 242 Python Solution

EasyHash TableStringSorting
Problem
#242
Pattern
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

Python
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

MeasureComplexity
TimeO(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
SpaceO(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

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

On study lists

This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.

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.

Get Stealth Interview