3. Valid Anagram
Decide whether rearranging the letters of one string could produce the other string. Every occurrence must be accounted for: matching the set of letters is insufficient if their counts differ.
The strings must have equal lengths and equal counts of every letter. For example, a repeated letter cannot be replaced by a different letter during rearrangement.
Example 1
Input
s="anagram", t="nagaram"
Output
true
Explanation: Every letter has equal multiplicity in both strings.
Example 2
Input
s="aab", t="abb"
Output
false
Explanation: The sets of letters match, but the counts of a and b do not.
Example 3
Input
s="", t=""
Output
true
Explanation: All 26 count differences are zero.
Constraints
0 <= s.length, t.length <= 105- Both strings contain only lowercase English letters a–z.
Hints
Hint 1
What information remains unchanged when letters are rearranged?
Hint 2
Represent each letter by its count.
Hint 3
Subtract one string’s counts from the other and test the final vector.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Imbalances cancel
"ab"
"ba"
true