Valid Anagram

EasyArrays and hashing

Two strings are anagrams when one is a rearrangement of the other: the same letters, each used the same number of times.

Given two strings s and t, return true if t uses exactly the letters of s, each the same number of times, in any order, and false if it does not.

Examples

Example 1
Input:  s = "night", t = "thing"
Output: true

Both use n, i, g, h and t once each.

Example 2
Input:  s = "hello", t = "hollo"
Output: false

hello has an e, and hollo has a second o instead.

Constraints

  • 1 ≤ s.length, t.length ≤ 5 × 10⁴
  • s and t use lowercase English letters only.

Stuck?

Hint 1

Strings of different lengths can never be anagrams. For the same length, what has to match is how many times each letter appears.

Hint 2

Count the letters of s up and the letters of t down, in an array of 26 or a Map. Every count must end at zero.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur