Valid Anagram
Examples
Example 1:
Input: s = "racecar", t = "carrace"
Output: true
Example 2:
Input: s = "jar", t = "jam"
Output: false
Example 1:
Input: s = "racecar", t = "carrace"
Output: true
Example 2:
Input: s = "jar", t = "jam"
Output: false
Given two strings s and t, return true if the two strings are anagrams of each other, otherwise return false.
An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.
s and t consist of lowercase English letters.If the strings have different lengths, they cannot be anagrams. Otherwise, count character frequencies using a 26-length array for lowercase letters, incrementing for s and decrementing for t. If all counts return to zero, the strings are anagrams. This handles the empty-string case and repeated characters directly.
Each position in the count array tracks the net difference between occurrences of a character in s and t. If the strings are anagrams, every character appears the same number of times, so all net differences are zero. Any mismatch leaves a non-zero count, correctly returning false.
O(n)O(1)class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
counts = [0] * 26
for i in range(len(s)):
counts[ord(s[i]) - ord('a')] += 1
counts[ord(t[i]) - ord('a')] -= 1
return all(count == 0 for count in counts)