Valid Anagram in Python Using Two Methods (Sorting & Counting)
Problem Explanation You are given two strings s and t. 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. Input: s = "anagram", t = "nagaram" True Input: s = "rat", t = "car" False Method
Sri Mahalakshmi
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
Found this useful? Share it!
Read the Full Story
Continue reading on Dev.to
Related Stories
Hiring Senior Full Stack Developer (Remote, USA)
about 2 hours ago
How I Built a Multi-Tenant WhatsApp Automation Platform Using n8n and WAHA
about 2 hours ago
I Built an Instant SEO Audit API โ Here's What I Learned About Technical SEO
about 3 hours ago
SJF4J: A Structured JSON Facade for Java
about 3 hours ago