Possible Bipartition

Medium

Topics
GraphBFSDFSUnion Find

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

1234
one groupthe other group
These 4 people and 3 dislikes do split into two groups. An edge joins two people who must end up apart, so once one person is placed every person they dislike is forced to the other side and there is never a choice to make. Everyone is connected through the dislikes, so a single pass of forced placements settles the whole group.
People are numbered from 1, and two people with no edge between them may share a group.
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

123
one groupthe other group
These 3 people and 3 dislikes cannot be split into two groups. Following those forced placements reaches a contradiction on the thickened edge, where both ends land in the same group — the signature of a cycle of odd length.
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

12345
one groupthe other group
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

  1. Build an adjacency list from the dislike pairs.
  2. Keep a group assignment per person, initially unassigned.
  3. For each person with no group yet, assign them one and propagate outward from them.
  4. Every neighbour of an assigned person must take the opposite group. If a neighbour is unassigned, assign and continue from it.
  5. If a neighbour already holds the same group as the person reaching it, an odd cycle exists, so return false.
  6. 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 True
SensAI
Beta
Tap the mic to stop voice mode