Imagine you're organizing a debate tournament and need to split n people (labeled from 1 to n) into two opposing teams of any size. However, some people have personal conflicts and absolutely refuse to be on the same team!

You're given an integer n representing the total number of people and an array dislikes where dislikes[i] = [a_i, b_i] indicates that person a_i dislikes person b_i (and vice versa - it's mutual). Your task is to determine if it's possible to split everyone into exactly two teams such that no two people who dislike each other end up on the same team.

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

Example: If person 1 dislikes person 2, and person 2 dislikes person 3, then we could put persons 1 and 3 on Team A, and person 2 on Team B.

Input & Output

example_1.py โ€” Basic case
$ Input: n = 4, dislikes = [[1,2],[1,3],[2,4]]
โ€บ Output: true
๐Ÿ’ก Note: We can divide into Team A: {1, 4} and Team B: {2, 3}. Person 1 dislikes 2 and 3 (both on Team B). Person 2 dislikes 1 (on Team A) and 4 (on Team A). No conflicts within teams.
example_2.py โ€” Impossible case
$ Input: n = 3, dislikes = [[1,2],[1,3],[2,3]]
โ€บ Output: false
๐Ÿ’ก Note: This creates a triangle where everyone dislikes everyone else. No matter how we divide into 2 teams, there will always be two people who dislike each other on the same team.
example_3.py โ€” Single person
$ Input: n = 1, dislikes = []
โ€บ Output: true
๐Ÿ’ก Note: With only one person and no dislikes, we can always form a valid bipartition (person 1 goes to either team).

Constraints

  • 1 โ‰ค n โ‰ค 2000
  • 0 โ‰ค dislikes.length โ‰ค 104
  • dislikes[i].length == 2
  • 1 โ‰ค dislikes[i][j] โ‰ค n
  • ai < bi
  • All the pairs of dislikes are unique

Visualization

Tap to expand
Bipartite Graph Problem VisualizationConflict Graph1234Dislikes: 1-2, 1-3, 2-4After DFS Coloring1234Team A: {1,4}, Team B: {2,3}Algorithm FlowBuild GraphCreate adjacency listStart DFSColor person 1 = Team AColor NeighborsPerson 2,3 = Team BContinue DFSPerson 4 = Team A๐ŸŽฏ Key Insight: This is bipartite graph 2-coloring - solvable in O(V + E) time!
Understanding the Visualization
1
Model as Graph
Each person is a node, dislikes are edges
2
Apply Graph Coloring
Try to color with 2 colors (teams)
3
DFS Traversal
Use DFS to assign alternating colors
4
Conflict Detection
If adjacent nodes have same color, return false
Key Takeaway
๐ŸŽฏ Key Insight: This problem is equivalent to determining if a graph is bipartite. We use graph coloring with DFS to assign people to two teams, ensuring no conflicts within teams.
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 24
42.0K Views
High Frequency
~15 min Avg. Time
1.9K 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