Classroom Seating Conflict - Problem

In a classroom of n students numbered 0 to n - 1, some pairs of students have conflicts and cannot sit in the same group.

You are given a 2D array conflicts where conflicts[i] = [u, v] means students u and v must be in different groups.

Return true if all students can be divided into exactly two groups such that no two conflicting students are in the same group, or false otherwise.

Input & Output

Example 1 — Possible Split
$ Input: n = 4, conflicts = [[0,1],[1,2],[2,3]]
Output: true
💡 Note: Group A: {0,2}, Group B: {1,3}. No conflicts within groups.
Example 2 — Odd Cycle
$ Input: n = 3, conflicts = [[0,1],[1,2],[0,2]]
Output: false
💡 Note: Triangle: all three conflict with each other. Cannot split into 2 groups.
Example 3 — No Conflicts
$ Input: n = 1, conflicts = []
Output: true
💡 Note: Single student, trivially split.

Constraints

  • 1 ≤ n ≤ 2 × 10^5
  • 0 ≤ conflicts.length ≤ 2 × 10^5
  • 0 ≤ u, v < n

Visualization

Tap to expand
Classroom Seating Conflict INPUT Students: n = 4 Conflict Graph: 0 1 2 3 conflict conflict conflict Can we split into 2 groups with no conflicts within a group? ALGORITHM STEPS 1 Build Conflict Graph Adjacency list from conflict pairs 2 BFS 2-Coloring Color node 0 as RED, neighbors BLUE 3 Check Conflicts Same-color neighbors? → false 4 Return Result All valid? → true Execution Trace: node color neighbors ok? 0 RED 1 ✓ 1 BLUE 0,2 ✓ 2 RED 1,3 ✓ 3 BLUE 2 ✓ No same-color conflicts found! FINAL RESULT Group Assignment: 🔴 Group A (RED) 0 2 🔵 Group B (BLUE) 1 3 No conflicts within groups! 0↔1 ✓ 1↔2 ✓ 2↔3 ✓ Output: true 💡 Key Insight: Two groups are possible if and only if the conflict graph is bipartite (no odd-length cycle). BFS 2-coloring checks this in O(V+E). Union-Find with complement nodes is an elegant alternative. TutorialsPoint - Classroom Seating Conflict | BFS 2-Coloring Approach
Asked in
Amazon 0 Google 0 Meta 0
6 Views
High Frequency
~15 min Avg. Time
0 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