Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 ith 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.
Example 1:
Input: hats = [[3,4],[4,5],[5]] Output: 1 Explanation: There is only one way to choose hats given the conditions. First person chooses hat 3, Second person chooses hat 4 and last one hat 5.
Example 2:
Input: hats = [[3,5,1],[3,5]] Output: 4 Explanation: There are 4 ways to choose hats: (3,5), (5,3), (1,3) and (1,5)
Example 3:
Input: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] Output: 24 Explanation: Each person can choose hats labeled from 1 to 4. Number of Permutations of (1,2,3,4) = 24.
Constraints:
n == hats.length1 <= n <= 101 <= hats[i].length <= 401 <= hats[i][j] <= 40hats[i] contains a list of unique integers.Problem summary: 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 ith 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Bit Manipulation
[[3,4],[4,5],[5]]
[[3,5,1],[3,5]]
[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
the-number-of-good-subsets)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1434: Number of Ways to Wear Different Hats to Each Other
class Solution {
public int numberWays(List<List<Integer>> hats) {
int n = hats.size();
int m = 0;
for (var h : hats) {
for (int v : h) {
m = Math.max(m, v);
}
}
List<Integer>[] g = new List[m + 1];
Arrays.setAll(g, k -> new ArrayList<>());
for (int i = 0; i < n; ++i) {
for (int v : hats.get(i)) {
g[v].add(i);
}
}
final int mod = (int) 1e9 + 7;
int[][] f = new int[m + 1][1 << n];
f[0][0] = 1;
for (int i = 1; i <= m; ++i) {
for (int j = 0; j < 1 << n; ++j) {
f[i][j] = f[i - 1][j];
for (int k : g[i]) {
if ((j >> k & 1) == 1) {
f[i][j] = (f[i][j] + f[i - 1][j ^ (1 << k)]) % mod;
}
}
}
}
return f[m][(1 << n) - 1];
}
}
// Accepted solution for LeetCode #1434: Number of Ways to Wear Different Hats to Each Other
func numberWays(hats [][]int) int {
n := len(hats)
m := 0
for _, h := range hats {
m = max(m, slices.Max(h))
}
g := make([][]int, m+1)
for i, h := range hats {
for _, v := range h {
g[v] = append(g[v], i)
}
}
const mod = 1e9 + 7
f := make([][]int, m+1)
for i := range f {
f[i] = make([]int, 1<<n)
}
f[0][0] = 1
for i := 1; i <= m; i++ {
for j := 0; j < 1<<n; j++ {
f[i][j] = f[i-1][j]
for _, k := range g[i] {
if j>>k&1 == 1 {
f[i][j] = (f[i][j] + f[i-1][j^(1<<k)]) % mod
}
}
}
}
return f[m][(1<<n)-1]
}
# Accepted solution for LeetCode #1434: Number of Ways to Wear Different Hats to Each Other
class Solution:
def numberWays(self, hats: List[List[int]]) -> int:
g = defaultdict(list)
for i, h in enumerate(hats):
for v in h:
g[v].append(i)
mod = 10**9 + 7
n = len(hats)
m = max(max(h) for h in hats)
f = [[0] * (1 << n) for _ in range(m + 1)]
f[0][0] = 1
for i in range(1, m + 1):
for j in range(1 << n):
f[i][j] = f[i - 1][j]
for k in g[i]:
if j >> k & 1:
f[i][j] = (f[i][j] + f[i - 1][j ^ (1 << k)]) % mod
return f[m][-1]
// Accepted solution for LeetCode #1434: Number of Ways to Wear Different Hats to Each Other
/**
* [1434] Number of Ways to Wear Different Hats to Each Other
*
* 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 the n people wear different hats to each other.
* Since the answer may be too large, return it modulo 10^9 + 7.
*
* Example 1:
*
* Input: hats = [[3,4],[4,5],[5]]
* Output: 1
* Explanation: There is only one way to choose hats given the conditions.
* First person choose hat 3, Second person choose hat 4 and last one hat 5.
*
* Example 2:
*
* Input: hats = [[3,5,1],[3,5]]
* Output: 4
* Explanation: There are 4 ways to choose hats:
* (3,5), (5,3), (1,3) and (1,5)
*
* Example 3:
*
* Input: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
* Output: 24
* Explanation: Each person can choose hats labeled from 1 to 4.
* Number of Permutations of (1,2,3,4) = 24.
*
*
* Constraints:
*
* n == hats.length
* 1 <= n <= 10
* 1 <= hats[i].length <= 40
* 1 <= hats[i][j] <= 40
* hats[i] contains a list of unique integers.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/
// discuss: https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/solutions/3112072/just-a-runnable-solution/
pub fn number_ways(hats: Vec<Vec<i32>>) -> i32 {
let mut dp = vec![vec![-1; 1024]; 41];
let n = hats.len();
let mut h2p = vec![vec![]; 41];
for (i, item) in hats.iter().enumerate().take(n) {
for &hat in item {
h2p[hat as usize].push(i);
}
}
Self::dfs_helper(&hats, &h2p, (1 << n) - 1, 1, 0, &mut dp)
}
fn dfs_helper(
hats: &Vec<Vec<i32>>,
h2p: &Vec<Vec<usize>>,
all_mask: i32,
hat: usize,
assigned_people: i32,
dp: &mut Vec<Vec<i32>>,
) -> i32 {
if assigned_people == all_mask {
return 1;
}
if hat > 40 {
return 0;
}
if dp[hat][assigned_people as usize] != -1 {
return dp[hat][assigned_people as usize];
}
let mut answer = Self::dfs_helper(hats, h2p, all_mask, hat + 1, assigned_people, dp);
for &p in &h2p[hat] {
if ((assigned_people >> p) & 1) == 1 {
continue;
}
answer +=
Self::dfs_helper(hats, h2p, all_mask, hat + 1, assigned_people | (1 << p), dp);
answer %= 1_000_000_007;
}
dp[hat][assigned_people as usize] = answer;
answer
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1434_example_1() {
let hats = vec![vec![3, 4], vec![4, 5], vec![5]];
let result = 1;
assert_eq!(Solution::number_ways(hats), result);
}
#[test]
fn test_1434_example_2() {
let hats = vec![vec![3, 5, 1], vec![3, 5]];
let result = 4;
assert_eq!(Solution::number_ways(hats), result);
}
#[test]
fn test_1434_example_3() {
let hats = vec![
vec![1, 2, 3, 4],
vec![1, 2, 3, 4],
vec![1, 2, 3, 4],
vec![1, 2, 3, 4],
];
let result = 24;
assert_eq!(Solution::number_ways(hats), result);
}
}
// Accepted solution for LeetCode #1434: Number of Ways to Wear Different Hats to Each Other
function numberWays(hats: number[][]): number {
const n = hats.length;
const m = Math.max(...hats.flat());
const g: number[][] = Array.from({ length: m + 1 }, () => []);
for (let i = 0; i < n; ++i) {
for (const v of hats[i]) {
g[v].push(i);
}
}
const f: number[][] = Array.from({ length: m + 1 }, () =>
Array.from({ length: 1 << n }, () => 0),
);
f[0][0] = 1;
const mod = 1e9 + 7;
for (let i = 1; i <= m; ++i) {
for (let j = 0; j < 1 << n; ++j) {
f[i][j] = f[i - 1][j];
for (const k of g[i]) {
if (((j >> k) & 1) === 1) {
f[i][j] = (f[i][j] + f[i - 1][j ^ (1 << k)]) % mod;
}
}
}
}
return f[m][(1 << n) - 1];
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.