MediumDepth-First SearchBreadth-First SearchUnion FindGraph

1 approach, code in every language

Problem description

There are n people numbered from 1 to n. Some pairs of people dislike each other, given as a list dislikes where dislikes[i] = [ai, bi] means person ai and person bi refuse to be in the same group.

You want to divide everyone into exactly two groups of any size such that no pair of people who dislike each other end up in the same group.

Return true if such a division is possible, and false otherwise.

Example 1

Input: n = 4, dislikes = [[1,2],[1,3],[2,4]]

Output: true

Group 1 = {1, 4} and Group 2 = {2, 3} satisfies every dislike: 1 is apart from 2 and 3, and 2 is apart from 4.

Example 2

Input: n = 3, dislikes = [[1,2],[1,3],[2,3]]

Output: false

The three people mutually dislike each other, forming a triangle. Two groups cannot separate three pairwise-conflicting people.

Constraints

  • 1 <= n <= 2000
  • 0 <= dislikes.length <= 10^4
  • dislikes[i].length == 2
  • 1 <= ai < bi <= n
  • All the pairs of dislikes are unique

After the pattern

Now solve one you haven't seen.

Kennel Split Into Two Yards is our own problem on the technique behind Possible Bipartition: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free