HardNo. 1125
Smallest Sufficient Team — LeetCode 1125 Python Solution
- Pattern
- Bit Manipulation
- Topics
- Bit Manipulation, Array, Dynamic Programming, Bitmask
- Reading time
- 5 min
- Source
- leetcode.com
The problem
In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has.
Example
- Input
- req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]]
- Output
- [0,2]
Python solution
class Solution:
def smallestSufficientTeam(
self, req_skills: List[str], people: List[List[str]]
) -> List[int]:
d = {s: i for i, s in enumerate(req_skills)}
m, n = len(req_skills), len(people)
p = [0] * n
for i, ss in enumerate(people):
for s in ss:
p[i] |= 1 << d[s]
f = [inf] * (1 << m)
g = [0] * (1 << m)
h = [0] * (1 << m)
f[0] = 0
for i in range(1 << m):
if f[i] == inf:
continue
for j in range(n):
if f[i] + 1 < f[i | p[j]]:
f[i | p[j]] = f[i] + 1
g[i | p[j]] = j
h[i | p[j]] = i
i = (1 << m) - 1
ans = []
while i:
ans.append(g[i])
i = h[i]
return ansComplexity
- Time
- O(2m × n)
- Space · auxiliary
- O(2m)
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1125. Smallest Sufficient Team is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0473 | Matchsticks to Square | Medium |
| 0526 | Beautiful Arrangement | Medium |
| 0638 | Shopping Offers | Medium |
| 0698 | Partition to K Equal Sum Subsets | Medium |
| 0805 | Split Array With Same Average | Hard |
| 0943 | Find the Shortest Superstring | Hard |
Frequently asked questions
- How hard is LeetCode 1125. Smallest Sufficient Team?
LeetCode 1125. Smallest Sufficient Team is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1125. Smallest Sufficient Team?
The Python solution on this page runs in O(2m × n).
- What is the space complexity of LeetCode 1125. Smallest Sufficient Team?
The Python solution on this page uses O(2m) auxiliary space.
- What topics does LeetCode 1125. Smallest Sufficient Team cover?
LeetCode 1125. Smallest Sufficient Team is tagged Bit Manipulation, Array, Dynamic Programming and Bitmask on LeetCode.