Valid Anagram Problem
#242
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 242.
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Constraints:
- 1 <= s.length, t.length <= 5 * 10^4
- s and t consist of lowercase English letters.
Solution
Approach: Count Letters
Two strings are anagrams exactly when every letter appears the same number of times in both. Since there are only 26 lowercase letters, a fixed array of counts is enough.
- If the lengths differ, return
falseright away. - Walk both strings together: for each index
i, add 1 to the count ofs[i]and subtract 1 from the count oft[i]. - The strings are anagrams if every count ends at 0.
Sorting both strings and comparing them also works, but takes O(n log n) time.
Complexity: O(n) time, where n is the length of s. O(1) extra space, as the count array always has 26 entries.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = [0] * 26 # count[c] = (times letter c appears in s) - (times in t)
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)