Example 1
- Input
- s = "anagram", t = "nagaram"
- Output
- true
Both strings contain three a characters and one each of n, g, r and m, so every character count matches and the answer is true.
Given two strings s and t, decide whether t is an anagram of s, meaning both strings contain exactly the same characters with exactly the same frequencies.
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Two strings are anagrams when one can be rearranged into the other, which means both strings have the same length and every character appears the same number of times in each of them.
1 <= s.length, t.length <= 5 * 10^4s and t consist of lowercase English letters only.Both strings contain three a characters and one each of n, g, r and m, so every character count matches and the answer is true.
Both strings contain r and a, but s contains t while t contains c. Those unmatched letters make the answer false.
The strings have different lengths, so rearranging one cannot produce the other. Return false before sorting or counting.
Both use the letters a and b and have length 3, but s has two a letters while t has only one. Matching sets and matching lengths do not establish matching frequencies.
Anagrams use the same bag of letters: order can change, but no letter can be added or removed. In anagram and nagaram, both bags contain three a letters and one each of g, m, n, and r. Sorting gives both bags one common order. Counting instead assigns a balance to each letter: add occurrences from s and subtract occurrences from t; every final balance must be zero. Temporary negative balances are allowed because a matching occurrence may appear later.
Reveal Sorting: intuition, complexity, and code
false immediately.s = "aacc" and t = "ccaa", where only exact frequencies make the answer true.a and a return true, while a and b return false.aab and abb return false.abx and bay balance after two indices, but must return false after reading the final letters.az and za return true, exercising slots 0 and 25.aab and abb use the same set but are not anagrams.n: -1 at index 0, yet later cancels it.abx and bay still differ at the last character.a.When a problem asks whether two inputs share the same composition, count frequencies with a hash map, or a fixed array when the alphabet is small, instead of sorting.