DEV Community

Santhoshi Mary A
Santhoshi Mary A

Posted on

Valid Anagram

Problem Statement

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

What is an Anagram?

An anagram is formed by rearranging the letters of another string using:

The same characters
The same frequency of characters
Possibly in a different order
Example 1

Input:

s = "anagram"
t = "nagaram"

Output:

true

Explanation:
Both strings contain the same characters with the same frequency.

Example 2

Input:

s = "rat"
t = "car"

Output:

false

Explanation:
The characters are different.

Constraints
1 <= s.length, t.length <= 5 * 10^4
s and t consist of lowercase English letters

Approach – Frequency Count (Optimized)

Instead of sorting, count the frequency of each character.

If both strings have identical character frequencies → they are anagrams.

Implementation (Using Dictionary)
class Solution:
def isAnagram(self, s, t):
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
Enter fullscreen mode Exit fullscreen mode

Why This is Better
Only one pass through both strings
No sorting required
More efficient for large inputs

Time Complexity: O(n)
Space Complexity: O(1) (since only 26 lowercase letters)

Dry Run Example

For:

s = "anagram"
t = "nagaram"

Character counts:

a → 3
n → 1
g → 1
r → 1
m → 1

After reducing counts using t, all frequencies become zero.

Therefore → True.

Top comments (0)