SDE & MLE Prep

886. Possible Bipartition

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