Problem Explanation
You are given two strings s and t.
Your task is to return True if t is an anagram of s, otherwise return False.
An anagram means both strings contain the same characters with the same frequency, just in a different order.
Example:
Input:
s = "anagram",t = "nagaram"
Output:TrueInput:
s = "rat",t = "car"
Output:False
Method 1: Sorting (Simplest Approach)
Idea
If two strings are anagrams, their sorted forms will be equal.
Code
class Solution:
def isAnagram(self, s, t):
return sorted(s) == sorted(t)
Explanation
-
sorted(s)→ sorts characters of strings -
sorted(t)→ sorts characters of stringt - If both sorted results are equal → strings are anagrams
Why Use This?
- Very easy to write and understand
- Best for beginners
- Clean one-line solution
Method 2: Counting Characters (Optimal Approach)
Idea
Count how many times each character appears in both strings and compare.
Code
class Solution:
def isAnagram(self, s, t):
if len(s) != len(t):
return False
count = [0] * 26
for i in range(len(s)):
count[ord(s[i]) - ord('a')] += 1
count[ord(t[i]) - ord('a')] -= 1
for num in count:
if num != 0:
return False
return True
Explanation (Step-by-Step)
if len(s) != len(t):
If lengths differ → cannot be anagramscount = [0] * 26
Create a list to store frequency of each characterfor i in range(len(s)):
Loop through both stringscount[...] += 1
Increase count for character inscount[...] -= 1
Decrease count for character intif num != 0:
If any count is not zero → not anagramreturn True
All counts match → valid anagram
Key Takeaway
- Sorting → simplest and clean
- Counting → more efficient and optimal
Top comments (0)