Problem
Valid Anagram
You are given two strings s and t.
Your task is to determine whether t is an anagram of s.
An anagram means both strings contain the same characters with the same frequency, just possibly in a different order.
Input: s = "anagram", t = "nagaram" → Output: true
Input: s = "rat", t = "car" → Output: false
Approach
To check if two strings are anagrams, we compare the frequency of each character.
Steps:
- If lengths of s and t are different, return False
- Count the frequency of each character in both strings
- Compare the counts
If all character counts match, the strings are anagrams.
Complexity:
Time Complexity: O(n)
Space Complexity: O(1)
def isAnagram(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
return all(c == 0 for c in count)
s = "anagram"
t = "nagaram"
print(isAnagram(s, t))
Top comments (0)