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 - DFS Graph Coloring INPUT Graph from dislikes: 1 2 3 4 1-2 1-3 2-4 n = 4 dislikes = [[1,2],[1,3],[2,4]] 4 people, 3 dislike pairs ALGORITHM STEPS 1 Build Graph Create adjacency list 2 Color node 1: RED Start DFS from node 1 3 Color neighbors: BLUE Nodes 2,3 get opposite color 4 Continue DFS Node 4 gets RED (opp of 2) DFS Coloring Result: 1 2 3 4 Group A Group B FINAL RESULT Two Groups Formed: Group A 1 4 Group B 2 3 Verification: 1-2: diff groups OK 1-3: diff groups OK 2-4: diff groups OK Output: true Bipartition possible! Key Insight: Graph bipartition is equivalent to 2-coloring. Use DFS to assign alternating colors to nodes. If any edge connects same-colored nodes, bipartition is impossible. No conflicts means success! Time: O(V+E) | Space: O(V) for color array and recursion stack TutorialsPoint - Possible Bipartition | DFS Graph Coloring Approach
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