Smallest Sufficient Team is on an Airbnb LeetCode tag list, tagged Bitmask (1 source). The task is the fewest people who together have every required skill. The state is the set of skills covered so far. With 16 skills or fewer, a set fits in an integer whose bit k says whether skill k is covered.
Predict
The state is the set of skills covered so far. With 16 skills, how many states can there be?
The masks are 0b001, 0b010 and 0b110. People 0 and 2 together give 0b111: every skill.
mask | has is the union of two sets, so 0b001 | 0b110 is 0b111, every skill.
import math# people[i]: a bitmask of the skills person i hasdef smallest_team(n_skills, people): full = (1 << n_skills) - 1 # size[mask]: the fewest people covering mask size = [math.inf] * (full + 1) # (previous mask, person), for the walk back took = [None] * (full + 1) size[0] = 0 for i, has in enumerate(people): # either direction works: mask | has | has == mask | has for mask in range(full, -1, -1): if size[mask] + 1 < size[mask | has]: size[mask | has] = size[mask] + 1 took[mask | has] = (mask, i) if size[full] == math.inf: return None team, mask = [], full while mask: mask, i = took[mask] team.append(i) return sorted(team)print(smallest_team(3, [0b001, 0b010, 0b110]))
[0, 2]
That's 2k states for k skills, times p people. With 16 skills, that's 65,536 states. With 30 random people it took 98 ms, and it matched trying every group of people on 300 small random cases.
Unlike the coin-change lesson's limited supply, the loop's direction doesn't matter here. Adding a person's skills a second time changes no mask, so nobody joins a team twice.
The same state, with the current junction added, gives the best simple path on a small graph with cycles. Sliding Puzzle, on Airbnb's list with a Dynamic Programming tag (1 source), is the other kind of state search. Each board is a state, and the fewest moves come from breadth-first search over boards, as in the lesson on breadth-first search on a grid.