922. Possible Bipartition
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks if we can partition n people into two groups such that no two people who dislike each other are in the same group. This is a classic graph problem in disguise.
Solution
Possible Bipartition in Python
from collections import deque
class Solution:
def possibleBipartition(self, n: int, dislikes: list[list[int]]) -> bool:
# Build adjacency list graph
# adj[i] contains a list of people disliked by person i
adj = [[] for _ in range(n + 1)]
for u, v in dislikes:
adj[u].append(v)
adj[v].append(u)
# colors[i] stores the group (color) of person i
# 0: not colored yet
# 1: group 1
# -1: group 2
colors = [0] * (n + 1)
# Iterate through each person to handle disconnected components
for i in range(1, n + 1):
# If this person is not colored yet, start a new traversal (BFS)
if colors[i] == 0:
q = deque([i])
colors[i] = 1 # Assign to group 1
while q:
u = q.popleft()
# For each person v disliked by u
for v in adj[u]:
# If v is not colored, color it with the opposite group
if colors[v] == 0:
colors[v] = -colors[u]
q.append(v)
# If v is already colored and is in the same group as u, it's a conflict
elif colors[v] == colors[u]:
return False
# If we successfully color everyone without conflicts
return True
Possible Bipartition in Java
class Solution {
public boolean possibleBipartition(int n, int[][] dislikes) {
// Build adjacency list graph
// adj.get(i) contains a list of people disliked by person i
List<List<Integer>> adj = new ArrayList<>(n + 1);
for (int i = 0; i <= n; i++) {
adj.add(new ArrayList<>());
}
for (int[] d : dislikes) {
adj.get(d[0]).add(d[1]);
adj.get(d[1]).add(d[0]);
}
// colors[i] stores the group (color) of person i
// 0: not colored yet
// 1: group 1
// -1: group 2
int[] colors = new int[n + 1];
// Iterate through each person to handle disconnected components
for (int i = 1; i <= n; i++) {
// If this person is not colored yet, start a new traversal (BFS)
if (colors[i] == 0) {
Queue<Integer> q = new LinkedList<>();
q.add(i);
colors[i] = 1; // Assign to group 1
while (!q.isEmpty()) {
int u = q.poll();
// For each person v disliked by u
for (int v : adj.get(u)) {
// If v is not colored, color it with the opposite group
if (colors[v] == 0) {
colors[v] = -colors[u];
q.add(v);
}
// If v is already colored and is in the same group as u, it's a conflict
else if (colors[v] == colors[u]) {
return false;
}
}
}
}
}
// If we successfully color everyone without conflicts
return true;
}
}
Possible Bipartition in C++
class Solution {
public:
bool possibleBipartition(int n, vector<vector<int>>& dislikes) {
// Build adjacency list graph
// adj[i] contains a list of people disliked by person i
vector<vector<int>> adj(n + 1);
for (const auto& d : dislikes) {
adj[d[0]].push_back(d[1]);
adj[d[1]].push_back(d[0]);
}
// colors[i] stores the group (color) of person i
// 0: not colored yet
// 1: group 1
// -1: group 2
vector<int> colors(n + 1, 0);
// Iterate through each person to handle disconnected components
for (int i = 1; i <= n; ++i) {
// If this person is not colored yet, start a new traversal (BFS)
if (colors[i] == 0) {
queue<int> q;
q.push(i);
colors[i] = 1; // Assign to group 1
while (!q.empty()) {
int u = q.front();
q.pop();
// For each person v disliked by u
for (int v : adj[u]) {
// If v is not colored, color it with the opposite group
if (colors[v] == 0) {
colors[v] = -colors[u];
q.push(v);
}
// If v is already colored and is in the same group as u, it's a conflict
else if (colors[v] == colors[u]) {
return false;
}
}
}
}
}
// If we successfully color everyone without conflicts
return true;
}
};
Possible Bipartition in TypeScript
function possibleBipartition(n: number, dislikes: number[][]): boolean {
// Build adjacency list graph
// adj[i] contains a list of people disliked by person i
const adj: number[][] = Array.from({ length: n + 1 }, () => []);
for (const d of dislikes) {
adj[d[0]].push(d[1]);
adj[d[1]].push(d[0]);
}
// colors[i] stores the group (color) of person i
// 0: not colored yet
// 1: group 1
// -1: group 2
const colors: number[] = new Array(n + 1).fill(0);
// Iterate through each person to handle disconnected components
for (let i = 1; i <= n; i++) {
// If this person is not colored yet, start a new traversal (BFS)
if (colors[i] === 0) {
const q: number[] = [i];
colors[i] = 1; // Assign to group 1
while (q.length > 0) {
const u = q.shift()!;
// For each person v disliked by u
for (const v of adj[u]) {
// If v is not colored, color it with the opposite group
if (colors[v] === 0) {
colors[v] = -colors[u];
q.push(v);
}
// If v is already colored and is in the same group as u, it's a conflict
else if (colors[v] === colors[u]) {
return false;
}
}
}
}
}
// If we successfully color everyone without conflicts
return true;
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.