Show problems as
Classic problem #242EasyHash TableStringSorting

Valid Anagram

Real-world version: Matching Letter Tally
Tracked in this browser only
Read Valid Anagram on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstHashmaps · Strings, animated step by step

A print shop sets words from loose metal type. The string tray lists the pieces of type sitting in a tray, one lowercase letter per piece, and the string target is the word a customer wants set.

The compositor may reorder the pieces freely but may not fetch a new piece or leave one out. Return true when the tray can be re-set to spell target exactly, and false otherwise.

Because each piece is a physical object, how many times a letter occurs matters: a tray holding two a pieces cannot set a word that needs three, even though both use the same letters.

Examples

Example 1

Input
tray = "cellar", target = "caller"
Output
true

Both words need one c, one a, two l, one e and one r, so the same pieces serve either arrangement.

Example 2

Input
tray = "aabb", target = "abbb"
Output
false

The tray and the word draw on the same two letters, but the word calls for three b pieces and the tray holds two.

Example 3

Input
tray = "zz", target = "z"
Output
false

Setting the word would leave a piece unused, which is not allowed.

Constraints

  • 1 <= tray.length, target.length <= 5 * 10^4
  • tray and target contain lowercase English letters only

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def can_respell(tray: str, target: str) -> bool:
Java
public boolean canRespell(String tray, String target)