Social feed~25 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-886bfs
You work on a social app. For a live event, the app opens two chat rooms, named room 0 and room 1, and puts every one of the n users in one of them. Users are numbered 0 to n - 1.
Some users have muted each other in pairs. Two users who muted each other must not share a room. Moderators want to know how many different ways the app can assign the users, so they can pick one at random. Either room may stay empty, and swapping the rooms counts as a different way.
Write ways_to_split(n, mutes).
n is the number of users.mutes[i] = [a, b] means users a and b muted each other, with a ≠ b.1,000,000,007.0 when no valid way exists.Input: n = 7, mutes = [[0, 1], [1, 2], [2, 3], [4, 5]]
Output: 8There are three groups of users who are linked by mutes: {0, 1, 2, 3}, {4, 5} and {6}. Place the first user of each group in room 0, and spread outwards with a queue.
| Step | Take | Queue after | Rooms of users 0 to 6 (- is not placed) | Groups |
|---|---|---|---|---|
| 1 | 0 | 1 | 0, 1, -, -, -, -, - | 1 |
| 2 | 1 | 2 | 0, 1, 0, -, -, -, - | 1 |
| 3 | 2 | 3 | 0, 1, 0, 1, -, -, - | 1 |
| 4 | 3 | 0, 1, 0, 1, -, -, - | 1 | |
| 5 | 4 | 5 | 0, 1, 0, 1, 0, 1, - | 2 |
| 6 | 5 | 0, 1, 0, 1, 0, 1, - | 2 | |
| 7 | 6 | 0, 1, 0, 1, 0, 1, 0 | 3 |
Each of the 3 groups can be placed either way round, so there are 2 × 2 × 2 = 8 ways.
Input: n = 3, mutes = [[0, 1], [1, 2], [2, 0]]
Output: 0Three users who all muted each other. Two of them must share a room, so there is no valid way.
Input: n = 3, mutes = []
Output: 8Nobody muted anybody, so each of the 3 users is a group of one, and each can go in either room: 8 ways.
1 ≤ n ≤ 100,0000 ≤ len(mutes) ≤ 100,000, and every row is [a, b] with 0 ≤ a, b < n and a ≠ bThere can be 100,000 users, so trying every assignment is 2^n choices, far more than any machine can try. The answer must place each user once and look at each mute a few times: n + m. The count itself needs a modulus, because 2^100000 has about 30,000 digits.