#1434
Number of Ways to Wear Different Hats to Each Other
HardArrayDynamic ProgrammingBit ManipulationBitmaskDynamic ProgrammingBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * 40 * 2^n) |
| Space | O(1) | O(2^n) |
💡
Intuition
Time O(n * 40 * 2^n)Space O(2^n)
The optimal solution uses dynamic programming with bitmasking to efficiently count the number of ways to assign hats. By representing the state of which people have been assigned hats using a bitmask, we can avoid redundant calculations and significantly reduce the number of combinations we need to check.
⚙️
Algorithm
3 steps- 1Step 1: Create a DP array where dp[mask] represents the number of ways to assign hats to the people represented by 'mask'.
- 2Step 2: Iterate through each hat type and update the DP array based on which people can wear that hat.
- 3Step 3: For each person that can wear the current hat, update the DP state by adding the number of ways from previous states.
solution.py16 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def countWays(hats):
5 n = len(hats)
6 dp = [0] * (1 << n)
7 dp[0] = 1
8 for hat in range(1, 41):
9 new_dp = dp[:]
10 for person in range(n):
11 if hat in hats[person]:
12 for mask in range(1 << n):
13 if (mask & (1 << person)) == 0:
14 new_dp[mask | (1 << person)] = (new_dp[mask | (1 << person)] + dp[mask]) % MOD
15 dp = new_dp
16 return dp[(1 << n) - 1]ℹ
Complexity note: The time complexity is O(n * 40 * 2^n) because we iterate over each hat (up to 40), and for each hat, we update the DP array for all possible combinations of people (2^n).
- 1Using bitmasking allows us to efficiently track which people have been assigned hats.
- 2Dynamic programming helps avoid recalculating the same states multiple times.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.