691. Stickers to Spell Word
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the minimum number of stickers to spell a given target string. We can use an infinite supply of each sticker and cut out individual letters. This problem can be modeled as a shortest path problem on a state graph. The states represent the set of characters we still need to form from the target string, and an edge exists between two states if we can transition from one to another by using one sticker. The weight of each edge is 1 (since we use one sticker). Our goal is to find the shortest path from the initial state (all characters of target needed) to the final state (no characters needed).
Solution
Stickers to Spell Word in Python
from collections import Counter
class Solution:
def minStickers(self, stickers: list[str], target: str) -> int:
n = len(target)
# Pre-process stickers into frequency maps.
sticker_counts = [Counter(s) for s in stickers]
# Memoization dictionary
memo = {}
def solve(mask):
# Base case: all characters are formed
if mask == 0:
return 0
# Check memoization
if mask in memo:
return memo[mask]
min_val = float('inf')
# Optimization: Find the first character we need to form
p = 0
for i in range(n):
if (mask >> i) & 1:
p = i
break
char_to_cover = target[p]
# Iterate through stickers that can provide this character
for i in range(len(stickers)):
if sticker_counts[i][char_to_cover] == 0:
continue
next_mask = mask
temp_sticker_count = sticker_counts[i].copy()
# Greedily apply the sticker
for j in range(n):
if (mask >> j) & 1:
char_needed = target[j]
if temp_sticker_count[char_needed] > 0:
next_mask &= ~(1 << j)
temp_sticker_count[char_needed] -= 1
res = solve(next_mask)
if res != -1:
min_val = min(min_val, 1 + res)
# Memoize and return
memo[mask] = min_val if min_val != float('inf') else -1
return memo[mask]
# Initial call
result = solve((1 << n) - 1)
return result
Stickers to Spell Word in Java
class Solution {
public int minStickers(String[] stickers, String target) {
int n = target.length();
int m = stickers.length;
// Memoization table: -1 indicates not computed, a large value for impossible.
int[] memo = new int[1 << n];
Arrays.fill(memo, -1);
// Pre-process stickers into frequency maps.
int[][] stickerCounts = new int[m][26];
for (int i = 0; i < m; i++) {
for (char c : stickers[i].toCharArray()) {
stickerCounts[i][c - 'a']++;
}
}
// Initial call to the recursive helper function.
int result = solve(target, stickerCounts, memo, (1 << n) - 1);
return result == Integer.MAX_VALUE ? -1 : result;
}
private int solve(String target, int[][] stickerCounts, int[] memo, int mask) {
// Base case: all characters in the target are formed.
if (mask == 0) {
return 0;
}
// Check memoization table.
if (memo[mask] != -1) {
return memo[mask];
}
int n = target.length();
int m = stickerCounts.length;
int minVal = Integer.MAX_VALUE;
// Find the first character in target that we need to form.
int p = 0;
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0) {
p = i;
break;
}
}
// Iterate through each sticker that can provide the character target[p].
for (int i = 0; i < m; i++) {
if (stickerCounts[i][target.charAt(p) - 'a'] == 0) {
continue; // This sticker can't help.
}
int nextMask = mask;
int[] currentStickerCount = Arrays.copyOf(stickerCounts[i], 26);
// Greedily apply the sticker.
for (int j = 0; j < n; j++) {
if ((mask & (1 << j)) != 0) { // If j-th char is needed.
int charIdx = target.charAt(j) - 'a';
if (currentStickerCount[charIdx] > 0) {
nextMask &= ~(1 << j); // Mark j-th char as formed.
currentStickerCount[charIdx]--;
}
}
}
int res = solve(target, stickerCounts, memo, nextMask);
if (res != Integer.MAX_VALUE) {
minVal = Math.min(minVal, 1 + res);
}
}
// Memoize and return.
memo[mask] = minVal;
return minVal;
}
}
Stickers to Spell Word in C++
class Solution {
public:
int minStickers(vector<string>& stickers, string target) {
int n = target.length();
int m = stickers.size();
// Memoization table: -2 means not computed, -1 means impossible.
vector<int> memo(1 << n, -2);
// Pre-process stickers into frequency maps.
vector<vector<int>> stickerCounts(m, vector<int>(26, 0));
for (int i = 0; i < m; ++i) {
for (char c : stickers[i]) {
stickerCounts[i][c - 'a']++;
}
}
// Initial call to the recursive helper function.
int result = solve(target, stickerCounts, memo, (1 << n) - 1);
return result;
}
private:
int solve(const string& target, const vector<vector<int>>& stickerCounts, vector<int>& memo, int mask) {
// Base case: all characters in the target are formed.
if (mask == 0) {
return 0;
}
// Check memoization table.
if (memo[mask] != -2) {
return memo[mask];
}
int n = target.length();
int m = stickerCounts.size();
int min_val = INT_MAX;
// Find the first character in target that we need to form (first set bit in mask).
int p = 0;
for (int i = 0; i < n; ++i) {
if ((mask >> i) & 1) {
p = i;
break;
}
}
// Iterate through each sticker that can provide the character target[p].
for (int i = 0; i < m; ++i) {
if (stickerCounts[i][target[p] - 'a'] == 0) {
continue; // This sticker can't help with the first needed char.
}
int next_mask = mask;
vector<int> currentStickerCount = stickerCounts[i]; // Create a mutable copy.
// Greedily apply the sticker to cover as many needed characters as possible.
for (int j = 0; j < n; ++j) {
if ((mask >> j) & 1) { // If j-th char is needed.
int char_idx = target[j] - 'a';
if (currentStickerCount[char_idx] > 0) {
next_mask &= ~(1 << j); // Mark j-th char as formed.
currentStickerCount[char_idx]--;
}
}
}
// Recursively call for the new state and update min_val.
int res = solve(target, stickerCounts, memo, next_mask);
if (res != -1) {
min_val = min(min_val, 1 + res);
}
}
// Memoize and return the result for the current state.
memo[mask] = (min_val == INT_MAX) ? -1 : min_val;
return memo[mask];
}
};
Stickers to Spell Word in TypeScript
function minStickers(stickers: string[], target: string): number {
const n = target.length;
const m = stickers.length;
// Memoization table: using a Map in JS/TS for sparse storage
const memo = new Map<number, number>();
// Pre-process stickers into frequency maps.
const stickerCounts: number[][] = Array(m).fill(0).map(() => Array(26).fill(0));
for (let i = 0; i < m; i++) {
for (const char of stickers[i]) {
stickerCounts[i][char.charCodeAt(0) - 'a'.charCodeAt(0)]++;
}
}
function solve(mask: number): number {
// Base case: all characters formed.
if (mask === 0) {
return 0;
}
// Check memoization.
if (memo.has(mask)) {
return memo.get(mask)!;
}
let minVal = Infinity;
// Find the first character in target that we need to form.
let p = 0;
for (let i = 0; i < n; i++) {
if ((mask >> i) & 1) {
p = i;
break;
}
}
const charToCoverCode = target.charCodeAt(p) - 'a'.charCodeAt(0);
// Iterate through stickers that can provide the character target[p].
for (let i = 0; i < m; i++) {
if (stickerCounts[i][charToCoverCode] === 0) {
continue;
}
let nextMask = mask;
const currentStickerCount = [...stickerCounts[i]];
// Greedily apply the sticker.
for (let j = 0; j < n; j++) {
if ((mask >> j) & 1) {
const charCode = target.charCodeAt(j) - 'a'.charCodeAt(0);
if (currentStickerCount[charCode] > 0) {
nextMask &= ~(1 << j);
currentStickerCount[charCode]--;
}
}
}
const res = solve(nextMask);
if (res !== -1) {
minVal = Math.min(minVal, 1 + res);
}
}
const result = minVal === Infinity ? -1 : minVal;
memo.set(mask, result);
return result;
}
return solve((1 << n) - 1);
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.