Valid Anagram
Real-world version: Matching Letter TallyThe statement here is our own: the same inputs, outputs and technique.
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.
def can_respell(tray: str, target: str) -> bool:public boolean canRespell(String tray, String target)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Find the DifferenceReal-world version: The Sort That Joined the TrayEasy
- Sort the PeopleReal-world version: Season Leaderboard From Two Parallel ListsEasy
- Find Resultant Array After Removing AnagramsReal-world version: Clearing Rearranged Labels Off the ShelfEasy
- Group AnagramsReal-world version: Bin Label FamiliesMedium