Back to articles
Valid Anagram in Python Using Two Methods (Sorting & Counting)

Valid Anagram in Python Using Two Methods (Sorting & Counting)

via Dev.to PythonSri 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: True Input: 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 string s sorted(t) → sorts characters of string t 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

Continue reading on Dev.to Python

Opens in a new tab

Read Full Article
2 views

Related Articles