Last updated on October 9th, 2024 at 06:14 pm
Here, We see Stickers to Spell Word LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Backtracking, Dynamic Programming
Level of Question
Hard
Stickers to Spell Word LeetCode Solution
Table of Contents
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.
1. Stickers to Spell Word LeetCode Solution 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; } };
2. Stickers to Spell Word LeetCode Solution 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. Stickers to Spell Word LeetCode Solution 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) }
4. Stickers to Spell Word LeetCode Solution 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]