Smallest Sufficient Team — LeetCode 1125 Python Solution

HardBit ManipulationArrayDynamic ProgrammingBitmask
Problem
#1125
Reading time
5 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(2^m \times n)
SpaceO(2^m) auxiliary

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

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(2^m \times n).
What is the space complexity of LeetCode 1125. Smallest Sufficient Team?
The Python solution on this page uses O(2^m) 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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview