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)