LeetCode Solutions
886. Possible Bipartition
Time: $O(|V| + |E|)$ Space: $O(|V|)$
enum Color { kWhite, kRed, kGreen };
class Solution {
public:
bool possibleBipartition(int n, vector<vector<int>>& dislikes) {
vector<vector<int>> graph(n + 1);
vector<Color> colors(n + 1, Color::kWhite);
for (const vector<int>& d : dislikes) {
const int u = d[0];
const int v = d[1];
graph[u].push_back(v);
graph[v].push_back(u);
}
// Reduce to 785. Is Graph Bipartite?
for (int i = 1; i <= n; ++i)
if (colors[i] == Color::kWhite &&
!isValidColor(graph, i, colors, Color::kRed))
return false;
return true;
}
private:
bool isValidColor(const vector<vector<int>>& graph, int u,
vector<Color>& colors, Color color) {
// The painted color should be same as the `color`
if (colors[u] != Color::kWhite)
return colors[u] == color;
colors[u] = color; // Always paint w/ `color`
// All children should have valid colors
for (const int v : graph[u])
if (!isValidColor(graph, v, colors,
color == Color::kRed ? Color::kGreen : Color::kRed))
return false;
return true;
}
};
enum Color { kWhite, kRed, kGreen }
class Solution {
public boolean possibleBipartition(int n, int[][] dislikes) {
List<Integer>[] graph = new List[n + 1];
Color[] colors = new Color[n + 1];
Arrays.fill(colors, Color.kWhite);
for (int i = 1; i <= n; ++i)
graph[i] = new ArrayList<>();
for (int[] d : dislikes) {
final int u = d[0];
final int v = d[1];
graph[u].add(v);
graph[v].add(u);
}
// Reduce to 785. Is Graph Bipartite?
for (int i = 1; i <= n; ++i)
if (colors[i] == Color.kWhite && !isValidColor(graph, i, colors, Color.kRed))
return false;
return true;
}
private boolean isValidColor(List<Integer>[] graph, int u, Color[] colors, Color color) {
// The painted color should be same as the `color`
if (colors[u] != Color.kWhite)
return colors[u] == color;
colors[u] = color; // Always paint w/ `color`
// All children should have valid colors
for (final int v : graph[u])
if (!isValidColor(graph, v, colors, color == Color.kRed ? Color.kGreen : Color.kRed))
return false;
return true;
}
}
from enum import Enum
class Color(Enum):
kWhite = 0
kRed = 1
kGreen = 2
class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
graph = [[] for _ in range(n + 1)]
colors = [Color.kWhite] * (n + 1)
for u, v in dislikes:
graph[u].append(v)
graph[v].append(u)
# Reduce to 785. Is Graph Bipartite?
def isValidColor(u: int, color: Color) -> bool:
# The painted color should be same as the `color`
if colors[u] != Color.kWhite:
return colors[u] == color
colors[u] = color # Always paint w/ `color`
# All children should have valid colors
childrenColor = Color.kRed if colors[u] == Color.kGreen else Color.kGreen
return all(isValidColor(v, childrenColor) for v in graph[u])
return all(colors[i] != Color.kWhite or isValidColor(i, Color.kRed)
for i in range(1, n + 1))