DEV Community

Navin S
Navin S

Posted on

πŸ”€ Valid Anagram (Step-by-Step Explanation)

The Valid Anagram problem is a fundamental string problem that checks whether two strings contain the same characters in a different order.


πŸ“Œ Problem Statement

Given two strings s and t, return true if t is an anagram of s, otherwise return false.

πŸ‘‰ An anagram means both strings have:

  • Same characters
  • Same frequency of each character

πŸ” Examples

Example 1:
Input: s = "anagram", t = "nagaram"
Output: true

Example 2:
Input: s = "rat", t = "car"
Output: false


🧠 Intuition

To check if two strings are anagrams:

  • Both strings must have the same length
  • The frequency of each character must match

πŸ”„ Approach 1 (Sorting Method – Simple)

Step-by-Step:

  1. Sort both strings
  2. Compare them

πŸ’» Python Code

```python id="a1"
def is_anagram(s, t):
return sorted(s) == sorted(t)

print(is_anagram("anagram", "nagaram"))




---

⚑ Complexity

Time Complexity: O(n log n)
Space Complexity: O(n)

---

πŸ”„ Approach 2 (Frequency Count – Optimal)

Step-by-Step:

1. If lengths are different β†’ return False
2. Count frequency of each character
3. Compare both counts

---

πŸ’» Python Code



```python id="a2"
def is_anagram(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())

print(is_anagram("anagram", "nagaram"))
Enter fullscreen mode Exit fullscreen mode

⚑ Complexity

Time Complexity: O(n)
Space Complexity: O(1) (only 26 lowercase letters)


πŸ”₯ Why This Works

  • Tracks exact frequency of each character
  • Ensures both strings match perfectly
  • Faster than sorting approach

⚠️ Follow-Up (Unicode Characters)

If strings contain Unicode characters:

πŸ‘‰ Use a dictionary (already done above)
πŸ‘‰ Avoid fixed-size arrays (since characters are not limited)


🏁 Conclusion

Valid Anagram is a simple yet important problem that teaches:

  • String manipulation
  • Hashing (frequency counting)
  • Optimization techniques

Top comments (0)