You have an unlimited supply of each sticker in stickers; every sticker shows one lowercase word. You may cut single letters out of the stickers you use and rearrange them.
Return the fewest stickers you need so that their letters can spell target. Unused letters are thrown away. If no number of stickers can spell it, return -1.
Example 1
Input: stickers = ["tan", "ice", "map"], target = "cat" Output: 2 Why: "ice" gives c; "tan" gives a and t
2 more examples and the constraints
Example 2
Input: stickers = ["dog", "pen"], target = "zoo" Output: -1 Why: no sticker has the letter z
Example 3
Input: stickers = ["ab", "bc"], target = "abba" Output: 2 Why: two "ab" stickers give a, a, b, b
Constraints
- 1 ≤ number of stickers ≤ 50
- 1 ≤ length of each sticker ≤ 10
- 1 ≤ length of target ≤ 15
- All words use lowercase English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Memoized search on leftover lettersO(states · s · t)
- DP over bitmasks of covered lettersO(2ᵗ · s · L · t)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 15-letter target | Verdict |
|---|---|---|---|
| Memoized search on leftover letters | O(states · s · t) | Passes; heavier constant from strings | |
| DP over bitmasks of covered letters | O(2ᵗ · s · L · t) | Best; plain integers, no memo map |
t = target length, s = number of stickers, L = sticker length.
Edge cases to test
- A target letter that no sticker has. Return -1. The DP never reaches the full mask.
- One sticker already spells the target. The answer is 1.
- A letter repeated many times. "aaaaaa" from a sticker "aab" needs 3 stickers, two a's at a time.
- Stickers with no useful letters. They never contain the first missing letter, so they are never tried.
Common mistakes
- Letting one sticker letter cover two target positions, which undercounts stickers.
- Trying every sticker from every state instead of only those with the first missing letter, which blows up the search.
- Returning dp[full] when it is still ∞ instead of -1.
How to talk through it
- 1Clarify. Can a sticker be reused? (Yes, without limit.) Is the target short? (At most 15 letters.)
- 2Pick a state. Fifteen letters means a bitmask of covered positions: 32,768 states.
- 3Cut the branching. Some sticker must cover the first uncovered letter, so only try those.
- 4Fill the DP. Moves only add bits, so masks in increasing order work; dp[new] = min(dp[new], dp[mask] + 1).
- 5Test out loud. Try a missing letter (-1), a single sticker that matches, and repeated letters.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?