DEV Community

Manoj Kumar
Manoj Kumar

Posted on

Valid Anagram – Python Solution

🔤 Valid Anagram – Python Solution

Hi All,

Today I solved a simple but important problem: Valid Anagram.


📌 Problem Statement

Given two strings s and t, check whether t is an anagram of s.

👉 An anagram means:

  • Both strings contain the same characters
  • Same frequency of each character
  • Order does not matter

🔍 Examples

Example 1:

s = "anagram"
t = "nagaram"
Enter fullscreen mode Exit fullscreen mode

Output:

True
Enter fullscreen mode Exit fullscreen mode

Example 2:

s = "rat"
t = "car"
Enter fullscreen mode Exit fullscreen mode

Output:

False
Enter fullscreen mode Exit fullscreen mode

💡 Approach

🔹 Method 1: Sorting (Simple)

  • Sort both strings
  • Compare results

💻 Python Code (Sorting)

def isAnagram(s, t):
    return sorted(s) == sorted(t)
Enter fullscreen mode Exit fullscreen mode

🔹 Method 2: Frequency Count (Optimal)

👉 Better approach using dictionary

  • Count characters in both strings
  • Compare frequencies

💻 Python Code (Dictionary)

def isAnagram(s, t):
    if len(s) != len(t):
        return False

    count = {}

    for char in s:
        count[char] = count.get(char, 0) + 1

    for char in t:
        if char not in count:
            return False
        count[char] -= 1

    return all(value == 0 for value in count.values())
Enter fullscreen mode Exit fullscreen mode

🔍 Dry Run

For:

s = "rat"
t = "tar"
Enter fullscreen mode Exit fullscreen mode

Steps:

  • Count s → {'r':1, 'a':1, 't':1}
  • Reduce using t → all become 0

Final Output:

True
Enter fullscreen mode Exit fullscreen mode

🖥️ Sample Output

Input: s = "anagram", t = "nagaram"
Output: True

Input: s = "rat", t = "car"
Output: False
Enter fullscreen mode Exit fullscreen mode

⚡ Complexity Analysis

Method Time Space
Sorting O(n log n) O(1)
Dictionary O(n) ✅ O(1)

🧠 Why this is important?

  • Tests string manipulation
  • Introduces frequency counting
  • Common in interviews

✅ Conclusion

This problem helped me understand:

  • Character frequency counting
  • Efficient string comparison
  • Optimizing solutions

🚀 A must-know problem for beginners!


Top comments (0)