DEV Community

VARUN
VARUN

Posted on

CA 14 - Valid Anagram


1.Problem Understanding
Given two strings:
Check if one is an anagram of the other
What is an Anagram?
*Same characters
*Same frequency
*Order doesn’t matter

Example
s = "anagram"
t = "nagaram"
Output:
true

2.Approach 1: Sorting (Basic)
Sort both strings and compare.
def isAnagram(s, t):
return sorted(s) == sorted(t)

3.Optimal Approach: Frequency Count

Count characters in both strings
Compare counts

4.Idea
If both strings have:
same characters
same frequency
They are anagrams

5.Example
s = "rat"
t = "tar"
Count:
r → 1
a → 1
t → 1
Same for both → ✅ anagram

Top comments (0)