Problem
Section titled “Problem”Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.
Example 1:
Input: s = "anagram", t = "nagaram"Output: trueExample 2:
Input: s = "rat", t = "car"Output: falseConstraints:
-
s.length,t.length sandtconsist of lowercase English letters.
Follow-up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Two strings are anagrams exactly when every letter occurs the same number of times in both. Sorting both strings and comparing works in , but with only 26 possible letters we can simply count.
One array is enough: add 1 for each letter of s and subtract 1 for each letter of t. The strings are anagrams if and only if every counter ends at 0 — a positive counter means s has a letter more often than t, a negative one the opposite.
Algorithm
Section titled “Algorithm”- If
s.size() != t.size(), returnfalse(different lengths can never match). - For each index
i:count[s[i] - 'a']++andcount[t[i] - 'a']--. - Return
trueif every entry ofcountis0, otherwisefalse.
Complexity
Section titled “Complexity”- Time: — one pass over the strings plus a 26-entry check.
- Space: — a fixed array of 26 counters.
Edge cases
Section titled “Edge cases”- Different lengths (
"a","ab"): rejected immediately by the length check, which also keepst[i]in range in the loop. - Same letters, different counts (
"aab","abb"): the counters foraandbend at+1and-1.
Follow-up: Unicode
Section titled “Follow-up: Unicode”With Unicode the alphabet is no longer 26 letters, so replace the array by a hash map from code point to count (unordered_map<char32_t, int>), after decoding both strings from UTF-8 into code points. The algorithm and its time stay the same; the space becomes for distinct characters. If the text may contain composed and decomposed forms of the same character (e.g. é vs e + combining accent), normalise both strings (for example to NFC) first.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { public: bool isAnagram(string s, string t) { if (s.size() != t.size()) return false; array<int, 26> count{}; for (size_t i = 0; i < s.size(); i++) { count[s[i] - 'a']++; count[t[i] - 'a']--; } for (int c : count) if (c != 0) return false; return true; }};class Solution { public boolean isAnagram(String s, String t) { if (s.length() != t.length()) return false; int[] count = new int[26]; for (int i = 0; i < s.length(); i++) { count[s.charAt(i) - 'a']++; count[t.charAt(i) - 'a']--; } for (int c : count) if (c != 0) return false; return true; }}class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False count = [0] * 26 for a, b in zip(s, t): count[ord(a) - ord('a')] += 1 count[ord(b) - ord('a')] -= 1 return not any(count)Give it a try first
Attempt the problem on LeetCode — the code will still be here.