Possible Bipartition (LeetCode 886): Solution and Explanation

Medium
Depth First Search
Breadth First Search
Union Find
Graph

Given n people and a list of pairs who dislike each other, decide whether everyone can be split into two groups so that no group contains a pair who dislike each other.

Intuition

Draw each person as a node and each dislike as an edge. A valid split means painting every node with one of two colors so that every edge joins two different colors. That is exactly the definition of a bipartite graph.

The choice for one person forces everything around them. If person 1 goes to group A, everyone person 1 dislikes must go to group B, everyone they dislike must go to A, and so on. There is no real decision to make after the first person in each connected piece.

So spread the forced choices with BFS. The only way to fail is to reach someone who already sits in the same group as the person you arrived from. That happens exactly when the graph has a cycle of odd length, like three people who all dislike each other.

People who are not connected to anyone you have searched are free. Their piece of the graph does not interact with the earlier ones, so start a fresh BFS from them and put them in group A.

Approach: BFS two-coloring

  1. Build an adjacency list with both directions of every dislike pair.
  2. Keep color[p] as 0 for unplaced, 1 for group A and -1 for group B.
  3. For each person start from 1 to n with color 0, set color[start] = 1 and push them on a queue.
  4. Pop u. For each v that u dislikes: if color[v] == color[u], return false; if color[v] == 0, set color[v] = -color[u] and push v.
  5. When every person has been placed without a clash, return true.

Step-by-step example

n = 4, dislikes = [[1,2],[1,3],[2,4]]
  1. The adjacency list is 1: [2, 3], 2: [1, 4], 3: [1], 4: [2].
  2. Person 1 is unplaced, so put 1 in group A and queue it.
  3. Pop 1. People 2 and 3 have no group, so both go to group B and join the queue.
  4. Pop 2 (group B). Person 1 is in A, which is fine. Person 4 has no group, so 4 goes to group A.
  5. Pop 3 and then 4. Each of their dislikes already sits in the opposite group.
  6. Everyone is placed: A = {1, 4}, B = {2, 3}. Return true.

Code: Python, Java, C++

1class Solution:
2    def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
3        graph = [[] for _ in range(n + 1)]
4        for a, b in dislikes:
5            graph[a].append(b)
6            graph[b].append(a)
7        color = [0] * (n + 1)
8        for start in range(1, n + 1):
9            if color[start] != 0:
10                continue
11            color[start] = 1
12            queue = deque([start])
13            while queue:
14                u = queue.popleft()
15                for v in graph[u]:
16                    if color[v] == color[u]:
17                        return False
18                    if color[v] == 0:
19                        color[v] = -color[u]
20                        queue.append(v)
21        return True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + E)

Each person is enqueued once and each dislike pair is looked at twice, once from each end.

Space

O(n + E)

The adjacency list stores every pair twice, plus the color array and the queue.

Other approaches

DFS two-coloring (time O(n + E), space O(n + E))

The same idea with recursion: color a node, then recursively give every uncolored neighbor the opposite color and fail on a same-color neighbor. Simple, but deep recursion can overflow the stack on a long chain of 2000 people.

Union-find with enemies (time O((n + E) α(n)), space O(n))

For each person, union everyone they dislike into one set. If a person ever ends up in the same set as someone they dislike, the split is impossible.

Common mistakes

  • Searching only from person 1. The dislike graph can be split into several pieces, and each needs its own BFS.
  • Adding each dislike in one direction only. The relation is mutual, so both people need the edge.
  • Allocating n slots instead of n + 1. People are numbered from 1, not 0.
  • Treating an already colored neighbor as a failure. Only a neighbor with the same color is a conflict; one with the opposite color is fine.

Frequently asked questions

Why does an odd cycle make the split impossible?

Walking around a cycle, the group has to flip at every edge. After an odd number of flips you return to the first person in the opposite group from where you started, which is a contradiction.

Is this the same as Is Graph Bipartite?

Yes, the core check is identical. Here the graph comes as an edge list with people numbered from 1, so you build the adjacency list yourself first.

Does it matter which group the first person goes to?

No. Swapping A and B in a valid split gives another valid split, so fixing the first person of each piece in group A loses nothing.

What if there are no dislikes at all?

Then every person is a separate piece with no edges, nothing can clash, and the answer is true.