Number of Ways to Wear Different Hats to Each Other - Problem

There are n people and 40 types of hats labeled from 1 to 40.

Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the i-th person.

Return the number of ways that n people can wear different hats from each other.

Since the answer may be too large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: hats = [[3,4],[4,5],[5]]
Output: 1
💡 Note: Only one way: person 0 wears hat 3, person 1 wears hat 4, person 2 wears hat 5
Example 2 — Multiple Options
$ Input: hats = [[3,5,1],[3,5]]
Output: 4
💡 Note: Four ways: (1,3), (1,5), (3,5), (5,3) where (x,y) means person 0 wears hat x, person 1 wears hat y
Example 3 — Single Person
$ Input: hats = [[1,2,3,4,5,6,7,8,9,10]]
Output: 10
💡 Note: One person can choose any of the 10 hats they like

Constraints

  • n == hats.length
  • 1 ≤ n ≤ 10
  • 1 ≤ hats[i].length ≤ 40
  • 1 ≤ hats[i][j] ≤ 40
  • All values in hats[i] are unique

Visualization

Tap to expand
Hats Distribution Problem Bottom-Up DP with Bitmask Approach INPUT n = 3 people, 40 hat types P0 Likes: 3 4 P1 Likes: 4 5 P2 Likes: 5 Input Array: hats = [ [3,4], [4,5], [5] ] Bitmask State: mask = 111 means all 3 people have hats fullMask = (1 << 3) - 1 = 7 ALGORITHM STEPS 1 Invert the mapping hat --> list of people 2 Initialize DP table dp[mask] = ways to assign 3 Iterate hats 1-40 Try assigning to each person 4 DP Transition Update mask when assigning DP Transition Table Hat Person Old Mask New Mask 3 P0 000 001 4 P1 001 011 5 P2 011 111 dp[111] = dp[7] = 1 way P0:hat3, P1:hat4, P2:hat5 FINAL RESULT Valid Assignment Found: P0 Hat 3 P1 Hat 4 P2 Hat 5 Output: 1 Only 1 valid way exists where each person gets a unique preferred hat P2 must have hat 5 (only choice) Key Insight: Iterate over hats (40) instead of people (n) to reduce state space. Bitmask represents which people have hats. Time: O(40 * 2^n * n), Space: O(2^n). Works because n is small (up to 10). dp[mask] counts ways to reach state where people in mask have been assigned unique hats. TutorialsPoint - Number of Ways to Wear Different Hats to Each Other | Bottom-Up DP with Bitmask
Asked in
Google 15 Amazon 12 Facebook 8
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen