#1125

Smallest Sufficient Team

Hard
ArrayDynamic ProgrammingBit ManipulationBitmaskDynamic ProgrammingBit Manipulation
LeetCode ↗

Approaches

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

Intuition

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

The optimal solution uses dynamic programming with bit manipulation to efficiently track which skills are covered by which combinations of people. This significantly reduces the number of combinations we need to check.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a bitmask for each person's skills.
  2. 2Step 2: Use a DP array to track the minimum team for each skill combination.
  3. 3Step 3: Iterate through each person and update the DP array based on their skills.
solution.py20 lines
1# Full working Python code
2from collections import defaultdict
3
4def smallestSufficientTeam(req_skills, people):
5    skill_to_index = {skill: i for i, skill in enumerate(req_skills)}
6    n = len(req_skills)
7    m = len(people)
8    dp = [None] * (1 << n)
9    dp[0] = []
10
11    for i in range(m):
12        person_mask = 0
13        for skill in people[i]:
14            person_mask |= (1 << skill_to_index[skill])
15        for j in range((1 << n) - 1, -1, -1):
16            if dp[j] is not None:
17                new_mask = j | person_mask
18                if dp[new_mask] is None or len(dp[new_mask]) > len(dp[j]) + 1:
19                    dp[new_mask] = dp[j] + [i]
20    return dp[(1 << n) - 1]

Complexity note: The time complexity is O(n * 2^n) because we iterate through each person and update the DP array for each possible skill combination. The space complexity is O(2^n) due to storing the DP array for all skill combinations.

  • 1Using bit manipulation allows us to efficiently represent and combine skill sets.
  • 2Dynamic programming helps to 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.