MediumDepth-First SearchBreadth-First SearchUnion FindGraph

Possible Bipartition

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now