Arrays and Hashing Hash map lookups

60. Valid Anagram

Easy 147 DSA Sheet

You are given two strings s and t. Return true if t uses exactly the same letters as s, each one the same number of times, and false otherwise. Put another way, return true when the letters of s can be rearranged to spell t.

The order of the letters does not matter, but how many times each letter appears does. So "aab" and "aba" match, while "aab" and "abb" do not.

Example 1

Input: s = "carthorse", t = "orchestra"

Output: true

Explanation: Both words have nine letters: one each of a, c, e, h, o, s and t, and two of r. Only the order is different.

Example 2

Input: s = "letter", t = "settle"

Output: false

Explanation: The two words have the same length and share most of their letters. But letter has an r where settle has an s.

Example 3

Input: s = "aabb", t = "ab"

Output: false

Explanation: t holds every letter that s holds, but only once each, while s has two of each. Strings of different lengths can never match.

Check your understanding

Work out the answer for this input before you write any code.

s = "aabc", t = "abcc"

Constraints

  • 1 ≤ s.length, t.length ≤ 105
  • s and t hold lowercase English letters only.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.