242. Valid Anagram
Asked at 34Bloomberg74Amazon65Microsoft63Google58Meta56Apple30tcs78IBM69Infosys68Zoho52Amadeus100Nokia100Yelp94American Express79Wipro73EPAM Systems72Ozon70Cognizant69Capgemini68Nagarro67Oracle60Affirm60Deloitte59Dell57Uber57Nvidia55Accenture54Spotify51Zopsmart49PayPal42Visa39DE Shaw38Cisco37Goldman Sachs21
Problem
Given two strings s and t, decide whether t is an anagram of s: the same letters with the same counts, possibly in a different order.
Example: s = "anagram", t = "nagaram" → true; s = "rat", t = "car" → false
Constraints: lowercase English letters; length ≤ 5·10⁴. Follow-up: what if the input is Unicode?
Anagrams have identical letter counts. Count up for s, down for t; every bucket must end at 0.
Complexity: O(n) time, O(1) space (26 letters).
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
cnt = [0] * 26
for a, b in zip(s, t):
cnt[ord(a) - 97] += 1
cnt[ord(b) - 97] -= 1
return all(c == 0 for c in cnt)
assert Solution().isAnagram("anagram", "nagaram") is True
assert Solution().isAnagram("rat", "car") is False
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] cnt = new int[26];
for (int i = 0; i < s.length(); i++) {
cnt[s.charAt(i) - 'a']++;
cnt[t.charAt(i) - 'a']--;
}
for (int c : cnt) if (c != 0) return false;
return true;
}
}
func isAnagram(s string, t string) bool {
if len(s) != len(t) {
return false
}
var cnt [26]int
for i := range s {
cnt[s[i]-'a']++
cnt[t[i]-'a']--
}
return cnt == [26]int{} // arrays compare by value
}