Stickers to Spell Word Problem

Problem

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.

Examples

Example 1:

1
2
3
4
5
6
7
8
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:

1
2
3
4
5
6
Input:
stickers = ["notice","possible"], target = "basicbasic"
Output:
 -1
Explanation:
We cannot form the target "basicbasic" from cutting letters from the given stickers.

Solution

Method 1 – DP with Memoization

Intuition

The main idea is to use dynamic programming with memoization to avoid recalculating the minimum stickers needed for the same sub-target. By representing the remaining target as a string, we can recursively try all sticker combinations and cache results for efficiency.

Approach

  1. Preprocess stickers into letter frequency maps.
  2. Use a recursive function to try all stickers and subtract their letters from the current target.
  3. Memoize results for each sub-target to avoid redundant calculations.
  4. If a sticker does not contribute to the current target, skip it.
  5. Return the minimum stickers needed, or -1 if impossible.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
    int minStickers(vector<string>& stickers, string target) {
        int n = stickers.size();
        vector<vector<int>> freq(n, vector<int>(26));
        for (int i = 0; i < n; ++i)
            for (char c : stickers[i]) freq[i][c - 'a']++;
        unordered_map<string, int> memo;
        memo[""] = 0;
        function<int(string)> dp = [&](string rem) {
            if (memo.count(rem)) return memo[rem];
            vector<int> tar(26);
            for (char c : rem) tar[c - 'a']++;
            int ans = INT_MAX;
            for (int i = 0; i < n; ++i) {
                if (!freq[i][rem[0] - 'a']) continue;
                string nxt;
                for (int j = 0; j < 26; ++j) {
                    if (tar[j] > freq[i][j])
                        nxt += string(tar[j] - freq[i][j], 'a' + j);
                }
                int tmp = dp(nxt);
                if (tmp != -1) ans = min(ans, 1 + tmp);
            }
            memo[rem] = (ans == INT_MAX) ? -1 : ans;
            return memo[rem];
        };
        return dp(target);
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
func minStickers(stickers []string, target string) int {
    n := len(stickers)
    freq := make([][26]int, n)
    for i, s := range stickers {
        for _, c := range s {
            freq[i][c-'a']++
        }
    }
    memo := map[string]int{"": 0}
    var dp func(string) int
    dp = func(rem string) int {
        if v, ok := memo[rem]; ok {
            return v
        }
        tar := [26]int{}
        for _, c := range rem {
            tar[c-'a']++
        }
        ans := 1 << 30
        for i := 0; i < n; i++ {
            if freq[i][rem[0]-'a'] == 0 {
                continue
            }
            nxt := ""
            for j := 0; j < 26; j++ {
                if tar[j] > freq[i][j] {
                    nxt += strings.Repeat(string('a'+j), tar[j]-freq[i][j])
                }
            }
            tmp := dp(nxt)
            if tmp != -1 && 1+tmp < ans {
                ans = 1 + tmp
            }
        }
        if ans == 1<<30 {
            memo[rem] = -1
        } else {
            memo[rem] = ans
        }
        return memo[rem]
    }
    return dp(target)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
    public int minStickers(String[] stickers, String target) {
        int n = stickers.length;
        int[][] freq = new int[n][26];
        for (int i = 0; i < n; ++i)
            for (char c : stickers[i].toCharArray()) freq[i][c - 'a']++;
        Map<String, Integer> memo = new HashMap<>();
        memo.put("", 0);
        return dp(target, freq, memo);
    }
    private int dp(String rem, int[][] freq, Map<String, Integer> memo) {
        if (memo.containsKey(rem)) return memo.get(rem);
        int[] tar = new int[26];
        for (char c : rem.toCharArray()) tar[c - 'a']++;
        int ans = Integer.MAX_VALUE;
        for (int i = 0; i < freq.length; ++i) {
            if (freq[i][rem.charAt(0) - 'a'] == 0) continue;
            StringBuilder nxt = new StringBuilder();
            for (int j = 0; j < 26; ++j)
                if (tar[j] > freq[i][j])
                    for (int k = 0; k < tar[j] - freq[i][j]; ++k)
                        nxt.append((char)('a' + j));
            int tmp = dp(nxt.toString(), freq, memo);
            if (tmp != -1) ans = Math.min(ans, 1 + tmp);
        }
        memo.put(rem, ans == Integer.MAX_VALUE ? -1 : ans);
        return memo.get(rem);
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
    fun minStickers(stickers: Array<String>, target: String): Int {
        val n = stickers.size
        val freq = Array(n) { IntArray(26) }
        for (i in 0 until n)
            for (c in stickers[i]) freq[i][c - 'a']++
        val memo = mutableMapOf("" to 0)
        fun dp(rem: String): Int {
            memo[rem]?.let { return it }
            val tar = IntArray(26)
            for (c in rem) tar[c - 'a']++
            var ans = Int.MAX_VALUE
            for (i in 0 until n) {
                if (freq[i][rem[0] - 'a'] == 0) continue
                var nxt = ""
                for (j in 0 until 26)
                    if (tar[j] > freq[i][j])
                        nxt += ("a" + j).repeat(tar[j] - freq[i][j])
                val tmp = dp(nxt)
                if (tmp != -1) ans = minOf(ans, 1 + tmp)
            }
            memo[rem] = if (ans == Int.MAX_VALUE) -1 else ans
            return memo[rem]!!
        }
        return dp(target)
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def minStickers(self, stickers: list[str], target: str) -> int:
        n = len(stickers)
        freq = [collections.Counter(s) for s in stickers]
        memo: dict[str, int] = {"": 0}
        def dp(rem: str) -> int:
            if rem in memo:
                return memo[rem]
            tar = collections.Counter(rem)
            ans = float('inf')
            for f in freq:
                if f[rem[0]] == 0:
                    continue
                nxt = ''.join([c * max(tar[c] - f[c], 0) for c in tar])
                tmp = dp(nxt)
                if tmp != -1:
                    ans = min(ans, 1 + tmp)
            memo[rem] = -1 if ans == float('inf') else ans
            return memo[rem]
        return dp(target)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
impl Solution {
    pub fn min_stickers(stickers: Vec<String>, target: String) -> i32 {
        use std::collections::{HashMap, HashSet};
        let n = stickers.len();
        let mut freq = vec![vec![0; 26]; n];
        for (i, s) in stickers.iter().enumerate() {
            for c in s.chars() {
                freq[i][(c as u8 - b'a') as usize] += 1;
            }
        }
        let mut memo = HashMap::new();
        memo.insert(String::new(), 0);
        fn dp(rem: &str, freq: &Vec<Vec<i32>>, memo: &mut HashMap<String, i32>) -> i32 {
            if let Some(&v) = memo.get(rem) { return v; }
            let mut tar = vec![0; 26];
            for c in rem.chars() { tar[(c as u8 - b'a') as usize] += 1; }
            let mut ans = i32::MAX;
            for f in freq {
                if f[(rem.chars().next().unwrap() as u8 - b'a') as usize] == 0 { continue; }
                let mut nxt = String::new();
                for j in 0..26 {
                    if tar[j] > f[j] {
                        nxt.push_str(&((b'a' + j as u8) as char).to_string().repeat((tar[j] - f[j]) as usize));
                    }
                }
                let tmp = dp(&nxt, freq, memo);
                if tmp != -1 { ans = ans.min(1 + tmp); }
            }
            let res = if ans == i32::MAX { -1 } else { ans };
            memo.insert(rem.to_string(), res);
            res
        }
        dp(&target, &freq, &mut memo)
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
    minStickers(stickers: string[], target: string): number {
        const n = stickers.length;
        const freq = stickers.map(s => {
            const f = Array(26).fill(0);
            for (const c of s) f[c.charCodeAt(0) - 97]++;
            return f;
        });
        const memo: Record<string, number> = { "": 0 };
        function dp(rem: string): number {
            if (rem in memo) return memo[rem];
            const tar = Array(26).fill(0);
            for (const c of rem) tar[c.charCodeAt(0) - 97]++;
            let ans = Infinity;
            for (let i = 0; i < n; i++) {
                if (!freq[i][rem.charCodeAt(0) - 97]) continue;
                let nxt = "";
                for (let j = 0; j < 26; j++) {
                    if (tar[j] > freq[i][j])
                        nxt += String.fromCharCode(97 + j).repeat(tar[j] - freq[i][j]);
                }
                const tmp = dp(nxt);
                if (tmp !== -1) ans = Math.min(ans, 1 + tmp);
            }
            memo[rem] = ans === Infinity ? -1 : ans;
            return memo[rem];
        }
        return dp(target);
    }
}

Complexity

  • ⏰ Time complexity: O(2^m * n * m) where m is the length of target and n is the number of stickers. Each subproblem is memoized, but the number of possible sub-targets is exponential in m.
  • 🧺 Space complexity: O(2^m + n * 26) for memoization and sticker frequency storage.