Fetching latest headlines…
Valid Anagram in Python Using Two Methods (Sorting & Counting)
NORTH AMERICA
πŸ‡ΊπŸ‡Έ United Statesβ€’March 22, 2026

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

0 views0 likes0 comments
Originally published byDev.to

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 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 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

Comments (0)

Sign in to join the discussion

Be the first to comment!