Skip to main content

Valid Anagram

Easy Subject: Arrays & Hashing
Time Complexity
O(N)
Space Complexity
O(1)

Problem Description

Problem Statement

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

Example 1:

  • Input: s = "anagram", t = "nagaram"
  • Output: true

Optimal Solution

Python

Approach: Hash Map / Frequency Counter

Count the frequency of characters in s and decrement for t. If all counts are zero, they are anagrams.

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False

        count = {}
        for char in s:
            count[char] = count.get(char, 0) + 1

        for char in t:
            if char not in count:
                return False
            count[char] -= 1
            if count[char] < 0:
                return False
        return True