Stickers to Spell Word LeetCode Solution

Last updated on March 2nd, 2025 at 02:47 pm

Here, we see a Stickers to Spell Word LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Backtracking, Dynamic Programming

Level of Question

Hard

Stickers to Spell Word LeetCode Solution

Stickers to Spell Word LeetCode Solution

1. Problem Statement

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.

2. Coding Pattern Used in Solution

The coding pattern used in all the provided implementations is “Breadth-First Search (BFS)” combined with “Dynamic Programming (DP)”. The problem involves finding the minimum number of stickers required to form the target string, which is a combinatorial optimization problem. BFS is used to explore all possible states (remaining target strings) level by level, while DP is used to store and reuse results of previously computed states to avoid redundant calculations.

3. Code Implementation in Different Languages

3.1 Stickers to Spell Word C++

class Solution {
public:
    int minStickers(vector<string>& stickers, string& target) {
        int n = size(stickers);

        unordered_set<string> visited;

        vector<vector<int>> s_frequencies(n, vector<int>(26, 0));
        for (int i = 0; i < n; ++i)
            for (auto& c : stickers[i])
                ++s_frequencies[i][c - 'a'];
        
        vector<int> t_frequency(26, 0);
        for (auto& c : target)
            ++t_frequency[c - 'a'];

        queue<vector<int>> q;
        q.push(t_frequency);

        for (int res = 0; size(q); ++res) {
            for (int k = size(q); k > 0; --k) {
                auto t_freq = q.front(); q.pop();

                string t_str;
                for (int i = 0; i < 26; ++i)
                    if (t_freq[i] > 0)
                        t_str += string(t_freq[i], i);

                if (t_str == "") return res;

                if (visited.count(t_str)) continue;
                visited.insert(t_str);

                char seeking = t_str[0];
                for (auto& v : s_frequencies) {
                    if (v[seeking] > 0) {
                        q.push(t_freq); // Push first to copy t_freq
                        for (int i = 0; i < 26; ++i)
                            q.back()[i] -= v[i];
                    }
                }
            }
        }

        return -1;
    }
};

3.2 Stickers to Spell Word Java

class Solution {
    public int minStickers(String[] stickers, String target) {
        int n = stickers.length;

        target = sortChars(target);
        for (int i = 0; i < n; ++i) stickers[i] = sortChars(stickers[i]);
        Queue<String> q = new LinkedList();
        q.offer(target);
        int steps = 0;
        Set<String> visited = new HashSet<>();
        while (!q.isEmpty()) {
            steps++;
            int size = q.size();
            while(size-- > 0) {
                String x = q.poll();
                for (int i = 0; i < n; ++i) {
                    String now = filter(x, stickers[i]);
                    if (now.isEmpty()) return steps;
                    if (!now.equals(x) && !visited.contains(now)) {
                        visited.add(now);
                        q.offer(now);
                    }
                }
            }
        }
        return -1;
    }
    public String filter(String a, String b) {
        StringBuilder ret = new StringBuilder();
        int idx = 0;

        for (char c : a.toCharArray()) {
            boolean found = false;
            while (idx < b.length() && b.charAt(idx) <= c) {
                if (b.charAt(idx++) == c) {
                    found = true;
                    break;
                }
            }
            if (!found) ret.append(c);
        }
        return ret.toString();
    }
    private String sortChars(String s) {
        char[] chars = s.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }
}

3.3 Stickers to Spell Word JavaScript

var minStickers = function(stickers, target) {
    let dp = new Map();
    const getStringDiff = (str1, str2) => {
        for(let c of str2) {
            if(str1.includes(c)) str1 = str1.replace(c, '');
        }
        return str1;
    }
    dp.set('', 0);

    function calcStickers(restStr) {
        if (dp.has(restStr)) return dp.get(restStr);
        let res = Infinity;
        for (let s of stickers.filter(s => s.includes(restStr[0]))) {
            let str = getStringDiff(restStr, s);
            res = Math.min(res, 1 + calcStickers(str));
        }
        dp.set(restStr, res === Infinity || res === 0 ? -1 : res);
        return dp.get(restStr);
    }
    return calcStickers(target)
}

3.4 Stickers to Spell Word Python

class Solution(object):
    def minStickers(self, stickers, target):
        n = len(target)
        maxMask = 1 << n
        dp = [float('inf')] * maxMask
        dp[0] = 0
        stickerCounts = []
        for sticker in stickers:
            stickerCounts.append(collections.Counter(sticker))
        for mask in range(maxMask):
            if dp[mask] == float('inf'):
                continue
            for i, stickerCount in enumerate(stickerCounts):
                if not any(c in stickerCount for c in target):
                    continue
                superMask = mask
                for c, freq in stickerCount.items():
                    for j, t in enumerate(target):
                        if c == t and not (superMask >> j & 1):
                            superMask |= 1 << j
                            freq -= 1
                            if freq == 0:
                                break
                dp[superMask] = min(dp[superMask], dp[mask] + 1)
        return -1 if dp[-1] == float('inf') else dp[-1]

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(2m * n * 26)O(2m + n * 26)
JavaO(2m * n * m)O(2m + n * m)
JavaScriptO(2m * n * m)O(2m + n * m)
PythonO(2m * n * m)O(2m + n * m)

where,
n is the number of stickers.
m is the length of target string.

  • Time Complexity:
    • The number of possible states for the target string is 2^m (all subsets of the target string of length m).
    • For each state, we iterate over all n stickers.
    • Processing each sticker involves iterating over the target string or its frequency array, which takes O(m) or O(26) (constant for C++).
    • Hence, the overall time complexity is O(2^m * n * m) or O(2^m * n * 26) for C++.
  • Space Complexity:
    • The visited set or dp map stores up to 2^m states.
    • The stickers and their frequencies take O(n * m) or O(n * 26) (constant for C++).
    • Hence, the overall space complexity is O(2^m + n * m) or O(2^m + n * 26) for C++.
Scroll to Top