AceYourInterviews
Checking sign-in…

3. Valid Anagram

FoundationFixed-alphabet frequency differences

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.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Imbalances cancel

"ab"
"ba"
true