DEV Community

Sri Mahalakshmi
Sri Mahalakshmi

Posted on

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

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)
Enter fullscreen mode Exit fullscreen mode

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 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
Enter fullscreen mode Exit fullscreen mode

Explanation (Step-by-Step)

  • if len(s) != len(t):
    If lengths differ → cannot be anagrams

  • count = [0] * 26
    Create a list to store frequency of each character

  • for i in range(len(s)):
    Loop through both strings

  • count[...] += 1
    Increase count for character in s

  • count[...] -= 1
    Decrease count for character in t

  • if num != 0:
    If any count is not zero → not anagram

  • return True
    All counts match → valid anagram


Key Takeaway

  • Sorting → simplest and clean
  • Counting → more efficient and optimal

Top comments (0)