Stickers To Spell Word Problem
Description
LeetCode Problem 691.
We 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.
Example 1:
Input: stickers = ["with","example","science"], target = "thehat"
Output: 3
Explanation:
We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.
Example 2:
Input: stickers = ["notice","possible"], target = "basicbasic"
Output: -1
Explanation:
We cannot form the target "basicbasic" from cutting letters from the given stickers.
Constraints:
- n == stickers.length
- 1 <= n <= 50
- 1 <= stickers[i].length <= 10
- 1 <= target <= 15
- stickers[i] and target consist of lowercase English letters.
Solution
Approach: DP over Subsets of Target Letters
The target has at most 15 letters, so we can describe "which letters of target are already spelled" with a bitmask: bit p is set when target[p] is covered. There are at most 215 masks.
Let dp[mask] be the fewest stickers that cover exactly the letters in mask, starting from dp[0] = 0. Applying one sticker to mask:
- Copy the sticker's letter counts. Walk through the uncovered positions
poftarget; if the sticker still has the lettertarget[p], use it and set bitp. - This gives
newMask, reachable withdp[mask] + 1stickers.
Using each sticker letter as soon as it fits is safe: positions holding the same letter are interchangeable, and taking as many as possible never hurts.
A sticker only adds bits, so newMask > mask. Processing masks in increasing order therefore finalizes dp[mask] before we extend it. The answer is dp[full], or -1 if it was never reached.
The pruning that keeps it fast: look at the first uncovered position first. Some sticker must supply target[first], and the order in which stickers are used does not matter, so we may as well use that sticker next. Only stickers containing target[first] are tried from mask. Without this rule, the same set of stickers is reached in every possible order.
For ["with","example","science"] and "thehat": "with" covers t and h, a second "with" covers the other t and h, and "example" covers e and a, so the answer is 3.
Complexity: O(2T · S · (T + 26)) time in the worst case and O(2T) space, where T is the length of target and S the number of stickers. The pruning usually leaves far fewer reachable masks.
class Solution:
def minStickers(self, stickers: List[str], target: str) -> int:
n = len(target)
target_letters = [ord(ch) - ord("a") for ch in target]
# Letter counts of each sticker.
sticker_counts = []
for sticker in stickers:
counts = [0] * 26
for ch in sticker:
counts[ord(ch) - ord("a")] += 1
sticker_counts.append(counts)
# dp[mask] = fewest stickers that spell the target letters at the set bits of mask (-1: not reached).
dp = [-1] * (1 << n)
dp[0] = 0
for mask in range(1 << n): # a sticker only adds bits, so smaller masks are final first
if dp[mask] == -1:
continue
first = 0 # the first target position still missing
while first < n and (mask >> first) & 1:
first += 1
if first == n:
continue
for counts in sticker_counts:
if counts[target_letters[first]] == 0:
continue # some sticker must supply this letter; trying only those avoids repeats
left = counts[:]
new_mask = mask
for p in range(n):
letter = target_letters[p]
if not (mask >> p) & 1 and left[letter] > 0:
left[letter] -= 1
new_mask |= 1 << p
if dp[new_mask] == -1 or dp[mask] + 1 < dp[new_mask]:
dp[new_mask] = dp[mask] + 1
return dp[(1 << n) - 1]
Now write it from memory
Close the write-up and solve it yourself against the tests.