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
Hat Assignment Problem: Count Valid WaysPeople & Preferences:Person 0Likes: [3,5,1]Person 1Likes: [3,5]Valid Assignments:(Person0=1, Person1=3)(Person0=1, Person1=5)(Person0=3, Person1=5)(Person0=5, Person1=3)Result: 4 waysEach person getsa different hatCount all valid assignments where no two people wear the same hat
Understanding the Visualization
1
Input
Each person has hat preferences
2
Process
Count ways to assign different hats
3
Output
Total number of valid assignments
Key Takeaway
🎯 Key Insight: Process hats instead of people and use bitmasks to track assignments efficiently
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