#691

Stickers to Spell Word

Hard
ArrayHash TableStringDynamic ProgrammingBacktrackingBit ManipulationMemoizationBitmaskBitmaskingDynamic ProgrammingBreadth-First Search (BFS)
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m * 2^m)
Space
O(1)
O(2^m)
💡

Intuition

Time O(n * m * 2^m)Space O(2^m)

The optimal solution uses dynamic programming and bitmasking to efficiently track which letters of the target can be formed. By representing the target as a bitmask, we can quickly check combinations of stickers and avoid redundant calculations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a frequency count for each sticker and the target.
  2. 2Step 2: Use a bitmask to represent the letters in the target that have been formed.
  3. 3Step 3: Use a queue for BFS to explore combinations of stickers, updating the bitmask as we go.
  4. 4Step 4: Track the minimum number of stickers used to reach the full target bitmask.
solution.py30 lines
1from collections import defaultdict, deque
2
3def minStickers(stickers, target):
4    target_count = [0] * 26
5    for char in target:
6        target_count[ord(char) - ord('a')] += 1
7
8    sticker_count = []
9    for sticker in stickers:
10        count = [0] * 26
11        for char in sticker:
12            count[ord(char) - ord('a')] += 1
13        sticker_count.append(count)
14
15    target_mask = (1 << len(target)) - 1
16    queue = deque([(0, 0)])
17    visited = set([0])
18    while queue:
19        mask, steps = queue.popleft()
20        for sticker in sticker_count:
21            new_mask = mask
22            for i in range(len(target)):
23                if (mask & (1 << i)) == 0 and sticker[ord(target[i]) - ord('a')] > 0:
24                    new_mask |= (1 << i)
25            if new_mask == target_mask:
26                return steps + 1
27            if new_mask not in visited:
28                visited.add(new_mask)
29                queue.append((new_mask, steps + 1))
30    return -1

Complexity note: This complexity arises from the number of states (2^m) we can have for the target letters, multiplied by the number of stickers (n) and the length of the target (m) for processing.

  • 1Using bitmasking allows us to efficiently track which letters of the target we have formed.
  • 2Dynamic programming helps avoid redundant calculations by storing previously computed results.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.