We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.

Given the integer n and the array dislikes where dislikes[i] = [aᵢ, bᵢ] indicates that the person labeled aᵢ does not like the person labeled bᵢ, return true if it is possible to split everyone into two groups in this way.

Input & Output

Example 1 — Basic Bipartite Case
$ Input: n = 4, dislikes = [[1,2],[1,3],[2,4]]
Output: true
💡 Note: Group 0: {1,4}, Group 1: {2,3}. Person 1 dislikes 2 and 3 (different groups), person 2 dislikes 4 (different groups). All constraints satisfied.
Example 2 — Non-bipartite Case
$ Input: n = 3, dislikes = [[1,2],[1,3],[2,3]]
Output: false
💡 Note: This forms a triangle where everyone dislikes everyone else. Impossible to split into two groups without putting two people who dislike each other in the same group.
Example 3 — No Constraints
$ Input: n = 5, dislikes = []
Output: true
💡 Note: No dislikes means everyone can go in any group. We can put anyone in group 0 and anyone in group 1.

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ dislikes.length ≤ 104
  • dislikes[i].length == 2
  • 1 ≤ ai < bi ≤ n
  • All pairs in dislikes are distinct

Visualization

Tap to expand
Possible Bipartition: Can We Split Into Two Groups?Inputn = 4dislikes = [[1,2], [1,3], [2,4]]People: 1, 2, 3, 4Conflicts between pairsGraph Model1234SolutionGroup 0{1, 4}Group 1{2, 3}✓ Valid SplitNo conflicts within groupsTransform dislike relationships into a graph, then check if it can be 2-coloredIf bipartite → possible bipartition (true), If odd cycle → impossible (false)Result: trueAlgorithm: DFS/BFS Graph Coloring - O(n + m) time
Understanding the Visualization
1
Input
n people and list of dislike pairs
2
Model as Graph
Create graph where edges represent dislikes
3
Check Bipartite
Use graph coloring to see if 2-group split is possible
Key Takeaway
🎯 Key Insight: A group can be split into two non-conflicting parts if and only if the dislike graph is bipartite
Asked in
Google 15 Facebook 12 Amazon 8
87.7K Views
Medium Frequency
~25 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen