Stickers to Spell Word - Problem
Imagine you have a collection of stickers, each containing a word made of lowercase English letters. Your goal is to spell out a given target string by cutting individual letters from these stickers and rearranging them.
The Rules:
- You can use each sticker multiple times (infinite quantities available)
- You can cut out individual letters from any sticker
- You need to find the minimum number of stickers required
- If it's impossible to spell the target, return
-1
Example: If you have stickers ["with", "example", "science"] and want to spell "thehat", you could use:
- 1 × "the" sticker → get 't', 'h', 'e'
- 1 × "example" sticker → get 'e'
- 1 × "science" → not needed
This would require 2 stickers minimum to spell "thehat".
Input & Output
example_1.py — Basic case
$
Input:
stickers = ["with", "example", "science"], target = "thehat"
›
Output:
3
💡 Note:
We can use 1 "with" sticker (provides t, h), 1 "example" sticker (provides e, a), and 1 "science" sticker (provides h, t). Total: 3 stickers.
example_2.py — Impossible case
$
Input:
stickers = ["notice", "possible"], target = "basicx"
›
Output:
-1
💡 Note:
The target contains 'x' which doesn't appear in any sticker, making it impossible to spell the target word.
example_3.py — Single sticker repeated
$
Input:
stickers = ["aa", "bb"], target = "aaaa"
›
Output:
2
💡 Note:
We need 2 "aa" stickers to get 4 'a' characters total to spell "aaaa".
Visualization
Tap to expand
Understanding the Visualization
1
Count Target Letters
First, count how many of each letter we need from the target string
2
Try Each Sticker
For each sticker, see which target letters it can provide
3
Recursive Subproblems
After using a sticker, solve for the remaining letters needed
4
Memoize States
Cache results to avoid recomputing the same letter count combinations
Key Takeaway
🎯 Key Insight: Convert the problem to character counting and use memoization on character count states to avoid redundant computations. The order of characters doesn't matter - only the counts do!
Time & Space Complexity
Time Complexity
O(N * 2^T)
Where N is number of stickers and T is target length. Each unique character count state is computed once.
✓ Linear Growth
Space Complexity
O(2^T)
Space for memoization table storing all possible character count combinations
✓ Linear Space
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code