886. Possible Bipartition
Asked at 11Microsoft33Amazon18Meta12Google11Bloomberg8.3TikTok56Samsung77Meesho67LinkedIn49Snap45Snowflake39
Problem
Split people 1…n into two groups (of any size) such that no pair in dislikes ends up in the same group. Decide whether that's possible.
Example: n = 4, dislikes = [[1,2],[1,3],[2,4]] → true; n = 3, dislikes = [[1,2],[1,3],[2,3]] → false
"Dislike" edges must cross groups → is the dislike graph bipartite? 2-color each component with BFS.
Complexity: O(V + E).
class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
g = defaultdict(list)
for a, b in dislikes:
g[a].append(b)
g[b].append(a)
color = {}
for s in range(1, n + 1):
if s in color:
continue
color[s] = 0
q = deque([s])
while q:
u = q.popleft()
for v in g[u]:
if v not in color:
color[v] = 1 - color[u]
q.append(v)
elif color[v] == color[u]:
return False
return True
assert Solution().possibleBipartition(4, [[1, 2], [1, 3], [2, 4]]) is True
assert Solution().possibleBipartition(3, [[1, 2], [1, 3], [2, 3]]) is False
class Solution {
public boolean possibleBipartition(int n, int[][] dislikes) {
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i <= n; i++) g.add(new ArrayList<>());
for (int[] d : dislikes) { g.get(d[0]).add(d[1]); g.get(d[1]).add(d[0]); }
int[] color = new int[n + 1];
Arrays.fill(color, -1);
for (int s = 1; s <= n; s++) {
if (color[s] != -1) continue;
color[s] = 0;
Deque<Integer> q = new ArrayDeque<>(List.of(s));
while (!q.isEmpty()) {
int u = q.poll();
for (int v : g.get(u)) {
if (color[v] == -1) { color[v] = 1 - color[u]; q.add(v); }
else if (color[v] == color[u]) return false;
}
}
}
return true;
}
}
func possibleBipartition(n int, dislikes [][]int) bool {
g := make([][]int, n+1)
for _, d := range dislikes {
g[d[0]] = append(g[d[0]], d[1])
g[d[1]] = append(g[d[1]], d[0])
}
color := make([]int, n+1) // 0 = uncolored, 1 / 2 = the two groups
for s := 1; s <= n; s++ {
if color[s] != 0 {
continue
}
color[s] = 1
q := []int{s}
for len(q) > 0 {
u := q[0]
q = q[1:]
for _, v := range g[u] {
if color[v] == 0 {
color[v] = 3 - color[u]
q = append(q, v)
} else if color[v] == color[u] {
return false
}
}
}
}
return true
}