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 <= 20000 <= dislikes.length <= 10^4dislikes[i].length == 21 <= ai < bi <= nAll the pairs of dislikes are uniqueSee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
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