AlgoFrames

Possible bipartition

Standard · Write code · about 12 min

There are n people, numbered 0 to n - 1. Each pair [a, b] in dislikes means person a and person b dislike each other and cannot be in the same team.

Return true if everyone can be split into two teams (either team may be empty) so that no pair of people who dislike each other share a team. Otherwise return false.

Example 1

Input:

[4,[[0,1],[0,2],[1,3]]]

Output:

true

Team 1 holds 0 and 3, team 2 holds 1 and 2.

Example 2

Input:

[3,[[0,1],[0,2],[1,2]]]

Output:

false

Three people who all dislike each other cannot fit two teams.

Constraints

  • 1 ≤ n ≤ 200 people, numbered 0 to n - 1
  • 0 ≤ dislikes.length ≤ 3n; each pair holds two valid people
  • A person may appear in many pairs; a pair may repeat

Learn the idea first: Bipartite check by 2-coloring, a visual lesson.

More Bipartite check by 2-coloring problems