Problem 691

Abstract / Summary

Determine the minimum number of stickers needed to form a target word using their letters.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0691.py

class Solution:
    def minStickers(self, stickers: List[str], target: str) -> int:
        candidates = defaultdict(set)
        for s in stickers:
            for c in s:
                candidates[c].add(s)

        # pre-check: all letters of target must be in candidates
        for t in target:
            if t not in candidates:
                return -1

        # lots of type conversions required ...
        todo  = [ tuple(list(target)) ]
        steps = 0
        stop  = False
        while not stop:
            steps += 1
            next   = set()

            for t in todo:
                need = t[0]

                for c in candidates[need]:
                    less = list(t)
                    # strip letters provided by current candidate
                    for x in c:
                        if x in less:
                            less.pop(less.index(x))

                    if less:
                        # next round
                        next.add(tuple(less))
                    else:
                        # we're done
                        stop = True
                        break

            todo = next

        return steps
41 lines | 1219 bytes | submitted April 22, 2024 | GitHub   17% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 51% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Bit Manipulation
  • Bitmask
  • Dynamic Programming
  • Hash Table
  • Memoization
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation solves the classic “minimum stickers to form a target” problem by exploring the space of remaining letters in a breadth-first manner. It first builds a reverse index that maps each character to the set of stickers containing that character. A preliminary feasibility check guarantees that every character of the target appears in at least one sticker; otherwise the function returns -1. The core loop iteratively expands the frontier of unfinished letter collections, counting the number of sticker layers required until the target is completely covered.

Construction of the character-to-sticker map

candidates = defaultdict(set)
for s in stickers:
    for c in s:
        candidates[c].add(s)

Each sticker is examined character by character, and the sticker itself is stored in a set associated with that character. This structure enables constant-time retrieval of all stickers that can contribute a needed letter during the search phase.

Feasibility pre-check

for t in target:
    if t not in candidates:
        return -1

By iterating over the target string, the code confirms that every required character has at least one supporting sticker. If any character is missing, the algorithm aborts early, handling the edge case where the target is impossible to assemble.

Initialization of the search frontier

todo  = [ tuple(list(target)) ]
steps = 0
stop  = False

The remaining letters are represented as a tuple, which is hashable and can be stored in a set for duplicate elimination. The initial frontier contains only the full target expressed as a tuple of its characters.

Breadth-first expansion loop

while not stop:
    steps += 1
    next   = set()

    for t in todo:
        need = t[0]

        for c in candidates[need]:
            less = list(t)
            # strip letters provided by current candidate
            for x in c:
                if x in less:
                    less.pop(less.index(x))

            if less:
                # next round
                next.add(tuple(less))
            else:
                # we're done
                stop = True
                break

    todo = next

The loop increments a step counter on each iteration, reflecting the number of sticker layers used so far. For every unfinished letter collection t in the current frontier, the algorithm selects the first character (need) as the pivot. All stickers that contain this pivot character are examined.

A temporary list less holds the remaining letters after the current sticker c is applied. The inner loop removes each occurrence of a character from less only if it is present, thereby handling duplicate letters correctly. If any letters remain, the reduced collection is added to the next set, ensuring that identical states are merged and not revisited. When less becomes empty, the target has been fully covered, the stop flag is set, and the outer loop terminates.

Edge cases addressed

The algorithm gracefully handles targets containing repeated characters because the removal step checks for the presence of each character before popping it, preserving the correct count of required instances.

When a sticker supplies more letters than needed, the removal loop simply ignores surplus characters, leaving the remaining list unchanged.

If multiple stickers can satisfy the same needed character, the breadth-first approach explores all possibilities in parallel, guaranteeing that the minimal number of stickers is discovered without exhaustive depth-first recursion.

The early feasibility check prevents unnecessary processing for impossible targets, covering the case where the target includes a character absent from all stickers.

Implicit performance optimizations

Storing stickers in a defaultdict(set) eliminates duplicate entries for the same character, reducing the number of inner-loop iterations.

Representing the remaining letters as a tuple enables fast hashing and deduplication when inserted into the next set, preventing exponential blow-up from revisiting identical states.

Choosing the first character of the tuple as the pivot (need = t[0]) focuses the expansion on a deterministic position, which reduces the branching factor compared to scanning the entire collection for a suitable character.

The algorithm increments the step counter only once per breadth level, avoiding per-sticker counting and simplifying the termination condition.

By converting the target string to a list and then to a tuple only once per frontier entry, the code minimizes repeated type conversions within the inner loops.

Overall, the combination of a reverse index, hashable state representation, and breadth-first traversal yields an efficient exploration of the solution space while naturally pruning redundant paths.

written by openai gpt

ELI5 - Simplified Explanation

Building words with stickers can be like trying to finish a puzzle. Imagine having a box of colorful stickers that each have different letters on them. You have a goal to spell out a specific word, and you want to use the fewest number of sticker sheets possible to make that happen.

The process starts by sorting the stickers into piles based on which letters they contain. If you need a letter that does not exist on any of the stickers, it is impossible to spell the word, so you stop right there.

To solve the puzzle, you start with the letters you need to find. You pick a sticker that has one of those letters and see what remains after covering the letter you needed. If you still have letters left to find, you keep track of those remaining pieces. You repeat this by looking at all the possible stickers you could pick next to help you cover the remaining letters. Each time you pick a sticker, it counts as one step. You keep track of all the different combinations of letters you still need until you finally finish the word. Once the last letter is covered by a sticker, you know exactly how many steps it took to complete the puzzle.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 4 | μ = 4.69 | σ = 2.05

Complexity Analysis

Time: exponential
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Rust Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
gouthampradhan Java
JoshCrozier JS
lkwq007 Python
ruoru Rust
suxrobGM C#
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
gouthampradhan Java
JoshCrozier JavaScript
lkwq007 Python
ruoru Rust
suxrobGM C#
wisdompeak C++
zfang399 C++
30 links | 16 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

2 hard
3 solutions   April 22, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality