Possible Bipartition
Medium
Topics
n people are numbered 1 to n. Each row of edges is a pair [a, b] meaning those two people dislike each other and must not share a group.
Return true if everyone can be split into two groups so that no pair who dislike each other end up together. Groups may be any size, including empty.
LeetCode names the second argument dislikes; the harness here calls it edges. People are labelled from 1.
Example 1
Input: n = 4, edges = [[1,2],[1,3],[2,4]] Output: true Explanation: Put 1 and 4 in one group and 2 and 3 in the other. Note 3 and 4 may share a group since they have no quarrel.
Example 2
Input: n = 3, edges = [[1,2],[1,3],[2,3]] Output: false Explanation: All three dislike each other, and three mutually hostile people cannot fit in two groups.
Example 3
Input: n = 5, edges = [[1,2],[2,3],[3,4],[4,5],[1,5]] Output: false Explanation: The dislikes form a cycle of odd length, which cannot be two-coloured.
Constraints
- 1 <= n <= 2000
- 0 <= edges.length <= 10^4
- edges[i].length == 2
- 1 <= edges[i][0] < edges[i][1] <= n
- No pair is repeated
Editorial — intuition, approach, complexity and pitfalls
Intuition
Treat each person as a node and each dislike as an edge, and the question becomes whether the graph can be coloured with two colours so that no edge joins two nodes of the same colour.
That is decidable by propagation, and the reason it needs no search is worth seeing: once one person is assigned a group, every person they dislike is forced into the other, and so on outward. There is never a choice to make, so there is nothing to backtrack over.
A contradiction appears exactly when propagation reaches someone who already has the same group as the person pushing them. At that moment you have found a cycle of odd length, and no odd cycle can be two-coloured — walking around it flips the colour an odd number of times and must disagree with where it started.
The graph can be in several disconnected pieces, so the propagation has to be started from every person not yet assigned. Forgetting that makes a disconnected hostile piece go unchecked and returns true wrongly.
Approach
- Build an adjacency list from the dislike pairs.
- Keep a group assignment per person, initially unassigned.
- For each person with no group yet, assign them one and propagate outward from them.
- Every neighbour of an assigned person must take the opposite group. If a neighbour is unassigned, assign and continue from it.
- If a neighbour already holds the same group as the person reaching it, an odd cycle exists, so return
false. - If every piece is processed without a clash, return
true.
Walkthrough
n = 4, edges = [[1,2],[1,3],[2,4]]
adjacency
1: 2 3
2: 1 4
3: 1
4: 2
propagate from 1, group A
1 -> A
2 must differ -> B
3 must differ -> B
from 2: 4 must differ from B -> A
assignments 1:A 2:B 3:B 4:A
no edge joins two of the same group, so true
note 3 and 4 are both assigned different groups here only
because of who they dislike; they have no edge between
them and could have shared one.
n = 3, edges = [[1,2],[1,3],[2,3]]
propagate from 1, group A
1 -> A
2 -> B
3 -> B
now the edge [2,3] joins two Bs
CLASH, so false
and that is the odd cycle: 1 - 2 - 3 - 1 has length 3.
why every person has to be a starting point
n = 4, edges = [[3,4]]
starting only from person 1 reaches nobody else, and
the pair [3,4] is never examined. Here it happens to be
satisfiable, but a disconnected triangle would not be.Complexity
- Time — O(n + e): each person is assigned once and each dislike examined from both ends.
- Space — O(n + e): the adjacency list and the group array.
Common Pitfalls
- Starting the propagation from person 1 only. A disconnected piece then goes unchecked.
- Indexing from 0 when the people are numbered from 1, which silently drops person
n. - Treating unassigned as a group. A sentinel distinct from both groups is needed, or an unassigned person looks like a clash.
- Checking only that neighbours differ, without assigning them, so the propagation never reaches further than one step.
- Searching over both choices for the first person. There is no choice — swapping the two groups gives the mirror answer — so backtracking is wasted work.
Full Solution — all languages
class Solution:
def possibleBipartition(self, n, edges):
from collections import deque
neighbours = [[] for _ in range(n + 1)]
for pair in edges:
neighbours[pair[0]].append(pair[1])
neighbours[pair[1]].append(pair[0])
group = [0] * (n + 1) # 0 unassigned, else 1 or 2
# The graph can be in several pieces, so every person is a candidate
# starting point.
for person in range(1, n + 1):
if group[person]:
continue
group[person] = 1
queue = deque([person])
while queue:
who = queue.popleft()
other = 3 - group[who]
for disliked in neighbours[who]:
if group[disliked] == group[who]:
return False # an odd cycle
if not group[disliked]:
group[disliked] = other
queue.append(disliked)
return Trueimport java.util.*;
class Solution {
public boolean possibleBipartition(int n, int[][] edges) {
List<List<Integer>> neighbours = new ArrayList<>();
for (int i = 0; i <= n; i++) neighbours.add(new ArrayList<>());
for (int[] pair : edges) {
neighbours.get(pair[0]).add(pair[1]);
neighbours.get(pair[1]).add(pair[0]);
}
int[] group = new int[n + 1];
// 0 unassigned, else 1 or 2
for (int person = 1; person <= n; person++) {
if (group[person] != 0) continue;
group[person] = 1;
Deque<Integer> queue = new ArrayDeque<>();
queue.add(person);
while (!queue.isEmpty()) {
int who = queue.poll();
int other = 3 - group[who];
for (int disliked : neighbours.get(who)) {
if (group[disliked] == group[who]) return false;
if (group[disliked] == 0) {
group[disliked] = other;
queue.add(disliked);
}
}
}
}
return true;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool possibleBipartition(int n, vector<vector<int>>& edges) {
vector<vector<int>> neighbours(n + 1);
for (auto& pair : edges) {
neighbours[pair[0]].push_back(pair[1]);
neighbours[pair[1]].push_back(pair[0]);
}
vector<int> group(n + 1, 0);
// 0 unassigned, else 1 or 2
for (int person = 1; person <= n; person++) {
if (group[person]) continue;
group[person] = 1;
queue<int> q;
q.push(person);
while (!q.empty()) {
int who = q.front();
q.pop();
int other = 3 - group[who];
for (int disliked : neighbours[who]) {
if (group[disliked] == group[who]) return false;
if (!group[disliked]) {
group[disliked] = other;
q.push(disliked);
}
}
}
}
return true;
}
};/**
* @param {number} n
* @param {number[][]} edges
* @return {boolean}
*/ var possibleBipartition = function(n, edges) {
const neighbours = [];
for (let i = 0; i <= n; i++) neighbours.push([]);
for (const [a, b] of edges) {
neighbours[a].push(b);
neighbours[b].push(a);
}
const group = new Array(n + 1).fill(0);
for (let person = 1; person <= n; person++) {
if (group[person]) continue;
group[person] = 1;
const queue = [person];
let head = 0;
while (head < queue.length) {
const who = queue[head++];
const other = 3 - group[who];
for (const disliked of neighbours[who]) {
if (group[disliked] === group[who]) return false;
if (!group[disliked]) {
group[disliked] = other;
queue.push(disliked);
}
}
}
}
return true;
};