All problems
0038EasyHash TableStringSorting

Matching Letter Tally

Tracked in this browser only
Write code

Trains the technique from

LeetCode 242Valid Anagram

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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