Stickers to Spell Word - Problem
You are given n different types of stickers. Each sticker has a lowercase English word on it.
You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.
Return the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.
Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.
Input & Output
Example 1 — Basic Case
$
Input:
stickers = ["with","example","science"], target = "thehat"
›
Output:
3
💡 Note:
We can use 2 "science" stickers (giving us 's', 'c', 'i', 'e', 'n', 'c', 'e') and 1 "example" sticker (giving us 'e', 'x', 'a', 'm', 'p', 'l', 'e') to spell "thehat". We need 't', 'h', 'e', 'h', 'a', 't'. From "science" we get 'e'. From "example" we get 'e', 'a'. We still need another approach - actually need "with" for 'w','i','t','h' and more stickers.
Example 2 — Simple Case
$
Input:
stickers = ["notice","possible"], target = "basicall"
›
Output:
-1
💡 Note:
We cannot spell "basicall" because we need 'r' and 'y' which are not available in any sticker, making it impossible.
Example 3 — Multiple Solutions
$
Input:
stickers = ["these","guess","about","garden","him"], target = "atomher"
›
Output:
3
💡 Note:
We can use "about" (a,b,o,u,t), "these" (t,h,e,s,e), "him" (h,i,m) to get enough letters. From "about" we get 'a','t','o'. From "these" we get 'h','e'. From "garden" we get 'r'. This gives us all letters for "atomher".
Constraints
- n == stickers.length
- 1 ≤ n ≤ 50
- 1 ≤ stickers[i].length ≤ 10
- 1 ≤ target.length ≤ 15
- stickers[i] and target consist of lowercase English letters
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code