Python 1125.py
class Solution:
def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:
# assign a ID to each required skill
need = {}
for r in req_skills:
need[r] = len(need)
all = (1 << len(need)) - 1 # bitmask of all skills
# bitmasks of revelant skills of each person
masks = []
for p in people:
current = 0
for s in p:
if s in need:
current |= 1 << need[s]
masks.append(current)
have = { 0: [] } # zero peeple, zero skills
for i, m in enumerate(masks):
if m == 0: # no relevant skill
continue
next = have.copy()
for h in have:
if (h & all) == all: # already complete
continue
more = (h | m) & all
if more == h: # no new skill
continue
# add person to team
team = have[h] + [ i ]
# new team with the skillset - or a smaller team
if more not in next or len(next[more]) > len(team):
next[more] = team
have = next
return have[all]
Difficulty
and has an acceptance rate of about 55% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Bit Manipulation
- Bitmask
- Dynamic Programming
AI Disclaimer
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.
Code Walkthrough
Overview
The implementation solves the “smallest sufficient team” problem by converting the set of required skills and each person’s skill list into compact bit-mask representations. A dynamic programming map (have) stores, for every reachable skill combination, the smallest team (list of indices) that achieves it. The algorithm iterates over each person, updates the map with new combinations that include the current person, and finally returns the team that covers all required skills.
Mapping Skills to Bit Positions
The first step creates a deterministic integer identifier for each required skill. This identifier is used to set a single bit in a mask.
need = {}
for r in req_skills:
need[r] = len(need)
all = (1 << len(need)) - 1 # mask with all required bits set
By using the length of need as the identifier, the mapping is built in a single pass and guarantees that each skill occupies a unique bit position.
Converting People’s Skill Lists to Masks
Each person’s list of skills is transformed into a mask that contains only the bits for required skills. Skills not present in need are ignored, which automatically discards irrelevant information.
masks = []
for p in people:
current = 0
for s in p:
if s in need:
current |= 1 << need[s]
masks.append(current)
If a person possesses no required skill, the resulting mask is zero. The later loop skips such entries, preventing unnecessary work.
Dynamic Programming Structure
The dictionary have holds the best (shortest) team for each skill subset encountered so far. It is initialized with the empty subset mapped to an empty team.
have = {0: []}
The core loop processes each person’s mask. For each existing subset h in have, the algorithm computes the union with the current person’s mask, restricts it to the required bits, and decides whether this new subset yields a smaller team.
for i, m in enumerate(masks):
if m == 0:
continue
next = have.copy()
for h in have:
if (h & all) == all:
continue
more = (h | m) & all
if more == h:
continue
team = have[h] + [i]
if more not in next or len(next[more]) > len(team):
next[more] = team
have = next
Handling Edge Cases
- Person without relevant skills - The
if m == 0: continueguard skips any person whose mask is zero, ensuring that the DP map is not polluted with redundant entries. - Already complete skill set - The condition
if (h & all) == all: continueprevents further expansion from a subset that already covers all required skills, avoiding unnecessary work. - No new skill contributed - The check
if more == h: continuediscards updates where the current person adds nothing new to the existing subset, which keeps the map size minimal.
These checks collectively guarantee that the algorithm only explores meaningful state transitions.
Performance Optimizations
The solution’s efficiency stems from several deliberate choices:
- Bit-mask representation - Encoding skill sets as integers enables constant-time union, intersection, and equality checks using bitwise operators. This eliminates the overhead of set operations or list traversals.
- Dictionary copying per iteration - By copying
haveintonextat the start of each person’s iteration, the algorithm preserves the previous state while safely adding new entries. This approach avoids in-place mutation that could interfere with ongoing iteration. - Pruning complete subsets - Skipping updates when a subset already satisfies all required skills (
if (h & all) == all) prevents the DP map from growing beyond the necessary frontier. - Skipping zero-contribution masks - Ignoring people with no relevant skills reduces the number of inner-loop executions, especially when the input contains many such entries.
- Selective insertion - The condition
if more not in next or len(next[more]) > len(team)ensures that only strictly smaller teams replace existing entries, keeping the map’s values minimal and preventing redundant larger teams from occupying space.
Together, these techniques keep the number of stored subsets bounded by the combinatorial space of required skills, while each transition is performed with cheap bitwise arithmetic.
Final Result
After processing all people, the dictionary entry keyed by all holds the smallest team that covers every required skill. The function returns this list of indices directly.
return have[all] ELI5 - Simplified Explanation
Imagine a big puzzle where every piece needs a special colored sticker. There is a list of all these special stickers that must be collected to finish the puzzle. Some people have stacks of these stickers, but other people do not have any at all. The goal is to pick the smallest group of people so that everyone's stickers add up to all the ones needed for the puzzle.
First, the code gives each of the required stickers a secret number. This makes it easy to keep track of who has which ones. Think of it like giving a label to every color. Then, the code looks at every person in line and turns their pile of stickers into a tiny secret code. If a person has a red sticker, their secret code reflects that. If they have a blue one, their code changes to include that too.
Next, the code starts building a team. It keeps a notebook that remembers the best groups of people found so far for every possible combination of stickers. It goes through each person one by one and asks if adding that person makes the team better. If the new person brings stickers that the group was missing, they get added to the team roster in the notebook.
The code keeps checking these groups and comparing them. If it finds a way to get all the needed stickers with fewer people, it updates the notebook. By the time it finishes looking at everyone, the notebook shows the perfect little group of people who together have exactly what is needed to finish the job.
Code Quality
Complexity Analysis
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
Other Solutions
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 | ||||||
| leetcode.ca | C++ | Java | Python | Go | TS | |||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| gouthampradhan | Java | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| lzl124631x | C++ | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| gouthampradhan | Java | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| lzl124631x | C++ | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 2670: Find the Distinct Difference Array
- problem 664: Strange Printer
- problem 765: Couples Holding Hands
Extra
- 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