Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.length1 <= n <= 501 <= stickers[i].length <= 101 <= target.length <= 15stickers[i] and target consist of lowercase English letters.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Dynamic Programming · Backtracking · Bit Manipulation
["with","example","science"] "thehat"
["notice","possible"] "basicbasic"
ransom-note)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #691: Stickers to Spell Word
class Solution {
public int minStickers(String[] stickers, String target) {
int n = target.length();
Deque<Integer> q = new ArrayDeque<>();
q.offer(0);
boolean[] vis = new boolean[1 << n];
vis[0] = true;
for (int ans = 0; !q.isEmpty(); ++ans) {
for (int m = q.size(); m > 0; --m) {
int cur = q.poll();
if (cur == (1 << n) - 1) {
return ans;
}
for (String s : stickers) {
int[] cnt = new int[26];
int nxt = cur;
for (char c : s.toCharArray()) {
++cnt[c - 'a'];
}
for (int i = 0; i < n; ++i) {
int j = target.charAt(i) - 'a';
if ((cur >> i & 1) == 0 && cnt[j] > 0) {
--cnt[j];
nxt |= 1 << i;
}
}
if (!vis[nxt]) {
vis[nxt] = true;
q.offer(nxt);
}
}
}
}
return -1;
}
}
// Accepted solution for LeetCode #691: Stickers to Spell Word
func minStickers(stickers []string, target string) (ans int) {
n := len(target)
q := []int{0}
vis := make([]bool, 1<<n)
vis[0] = true
for ; len(q) > 0; ans++ {
for m := len(q); m > 0; m-- {
cur := q[0]
q = q[1:]
if cur == 1<<n-1 {
return
}
for _, s := range stickers {
cnt := [26]int{}
for _, c := range s {
cnt[c-'a']++
}
nxt := cur
for i, c := range target {
if cur>>i&1 == 0 && cnt[c-'a'] > 0 {
nxt |= 1 << i
cnt[c-'a']--
}
}
if !vis[nxt] {
vis[nxt] = true
q = append(q, nxt)
}
}
}
}
return -1
}
# Accepted solution for LeetCode #691: Stickers to Spell Word
class Solution:
def minStickers(self, stickers: List[str], target: str) -> int:
n = len(target)
q = deque([0])
vis = [False] * (1 << n)
vis[0] = True
ans = 0
while q:
for _ in range(len(q)):
cur = q.popleft()
if cur == (1 << n) - 1:
return ans
for s in stickers:
cnt = Counter(s)
nxt = cur
for i, c in enumerate(target):
if (cur >> i & 1) == 0 and cnt[c] > 0:
cnt[c] -= 1
nxt |= 1 << i
if not vis[nxt]:
vis[nxt] = True
q.append(nxt)
ans += 1
return -1
// Accepted solution for LeetCode #691: Stickers to Spell Word
use std::collections::{HashSet, VecDeque};
impl Solution {
pub fn min_stickers(stickers: Vec<String>, target: String) -> i32 {
let mut q = VecDeque::new();
q.push_back(0);
let mut ans = 0;
let n = target.len();
let mut vis = HashSet::new();
vis.insert(0);
while !q.is_empty() {
for _ in 0..q.len() {
let state = q.pop_front().unwrap();
if state == (1 << n) - 1 {
return ans;
}
for s in &stickers {
let mut nxt = state;
let mut cnt = [0; 26];
for &c in s.as_bytes() {
cnt[(c - b'a') as usize] += 1;
}
for (i, &c) in target.as_bytes().iter().enumerate() {
let idx = (c - b'a') as usize;
if (nxt & (1 << i)) == 0 && cnt[idx] > 0 {
nxt |= 1 << i;
cnt[idx] -= 1;
}
}
if !vis.contains(&nxt) {
q.push_back(nxt);
vis.insert(nxt);
}
}
}
ans += 1;
}
-1
}
}
// Accepted solution for LeetCode #691: Stickers to Spell Word
function minStickers(stickers: string[], target: string): number {
const n = target.length;
const q: number[] = [0];
const vis: boolean[] = Array(1 << n).fill(false);
vis[0] = true;
for (let ans = 0; q.length; ++ans) {
const qq: number[] = [];
for (const cur of q) {
if (cur === (1 << n) - 1) {
return ans;
}
for (const s of stickers) {
const cnt: number[] = Array(26).fill(0);
for (const c of s) {
cnt[c.charCodeAt(0) - 97]++;
}
let nxt = cur;
for (let i = 0; i < n; ++i) {
const j = target.charCodeAt(i) - 97;
if (((cur >> i) & 1) === 0 && cnt[j]) {
nxt |= 1 << i;
cnt[j]--;
}
}
if (!vis[nxt]) {
vis[nxt] = true;
qq.push(nxt);
}
}
}
q.splice(0, q.length, ...qq);
}
return -1;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Mutable state leaks between branches.
Usually fails on: Later branches inherit selections from earlier branches.
Fix: Always revert state changes immediately after recursive call.