Introduction
String problems are very common in programming, and one of the most basic yet important problems is checking whether two strings are anagrams.
This problem helps build a strong understanding of character frequency and hashing.
Problem Statement
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
What is an Anagram?
Two strings are anagrams if:
- They contain the same characters
- With the same frequency
- But possibly in a different order
Example 1:
Input:
s = "anagram"
t = "nagaram"
Output:
True
Example 2:
Input:
s = "rat"
t = "car"
Output:
False
Approach 1: Sorting Method
- Sort both strings
- Compare the sorted results
Python Implementation
def is_anagram(s, t):
return sorted(s) == sorted(t)
# Example usage
print(is_anagram("anagram", "nagaram"))
Approach 2: Using Dictionary (Efficient)
- Count frequency of each character
- Compare frequencies
Python Implementation
def is_anagram(s, t):
if len(s) != len(t):
return False
count = {}
# Count characters in s
for ch in s:
count[ch] = count.get(ch, 0) + 1
# Subtract using t
for ch in t:
if ch not in count:
return False
count[ch] -= 1
# Check all values are zero
for val in count.values():
if val != 0:
return False
return True
# Example usage
print(is_anagram("rat", "car"))
Approach 3: Using Counter (Simplest)
from collections import Counter
def is_anagram(s, t):
return Counter(s) == Counter(t)
Key Points
- Length must be equal
- Frequency of characters must match
- Dictionary approach is more efficient than sorting
- Very common interview question
Conclusion
The Valid Anagram problem is a simple yet powerful example of using frequency counting. It teaches how to efficiently compare data using hashing instead of relying on slower sorting methods.
Understanding this problem helps in solving many advanced string and hashing problems.
Top comments (0)