Valid Anagram

Easy· frequency count

Problem

Decide whether string t is an anagram of string s, meaning it uses exactly the same characters with the same frequencies, just in a different order.

Examples

Input: s = "listen", t = "silent"
Output: true
Input: s = "rat", t = "car"
Output: false
t has a "c" that s lacks, and s has a "t" that t lacks.

Constraints

  • • 1 <= s.length, t.length <= 5 * 10^4
  • • Lowercase English letters only

Hints & approach

Hint 1

Different lengths mean the answer is immediately false.

Hint 2

Two strings are anagrams exactly when their character counts match.

Hint 3

With only 26 letters, a fixed-size array of counts is enough.

Approachtry the hints first

If the lengths differ, return false. Otherwise use a 26-slot count array: increment for each character of s and decrement for each character of t. If every slot ends at zero, the strings contain identical multisets of characters. For arbitrary Unicode input, swap the array for a hash map.

Time O(n) · Space O(1) (26 counters)

Output
Call your solution with a test case and Run. For the full judge, submit on LeetCode.