1552. Peaceful Guest Lists

Medium3.5 points estimatedBitmaskEnumerationGraph

You plan a party with guests numbered from 0 to n - 1. Each pair [u, v] in conflicts means guests u and v refuse to attend together (the pair may be listed more than once or in both orders). A guest list is peaceful if it contains no conflicting pair.

Count the peaceful guest lists, i.e. the subsets of guests with no two members in conflict. The empty list counts as one peaceful list, and a list with a single guest is always peaceful. Return the number as an int.

Hint: store each guest's conflicts as a bitmask, then walk through all 2^n subsets; a subset is peaceful when the subset without its lowest member is peaceful and the lowest member has no conflict with the rest.

Intended complexity: O(2^n + m) time and O(2^n) space.

Example 1

Input:
n = 4, conflicts = [[0,1],[1,2]]
Output:
10
Explanation:

Subsets of guests 0,1,2 avoiding the pairs 0-1 and 1-2 are {}, {0}, {1}, {2}, {0,2}, and guest 3 doubles that to 10.

Example 2

Input:
n = 3, conflicts = []
Output:
8
Explanation:

With no conflicts every one of the 2^3 subsets is peaceful, giving 8.

Example 3

Input:
n = 3, conflicts = [[0,1],[1,2],[0,2]]
Output:
4
Explanation:

Everyone conflicts with everyone, so only the empty list and the three single-guest lists work, giving 4.

Constraints

1 ≤ n ≤ 16

0 ≤ conflicts.length ≤ 120

conflicts[i] = [u, v], 0 ≤ u, v < n, u ≠ v

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(2^n + m)
Space
O(2^n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…