Check if two-group seating is possible
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: Check if two-group seating is possible evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= n <= 10^5 where n = len(adj)
- 0 <= adj[i][k] < n (indices are valid guests)
- Total number of adjacency entries (edges counted from both sides) up to ~2*10^5
- Input may contain disconnected components, duplicate entries, or self-loops
- Return a boolean
Examples
Input: ([[1], [0]],)
Expected Output: True
Explanation: Two guests who know each other go into different groups — bipartite.
Input: ([[1, 2], [0, 2], [0, 1]],)
Expected Output: False
Explanation: Triangle (odd cycle): three mutual acquaintances cannot be split into two groups.
Input: ([],)
Expected Output: True
Explanation: No guests — vacuously seatable.
Input: ([[]],)
Expected Output: True
Explanation: One isolated guest — trivially seatable in one group.
Input: ([[0]],)
Expected Output: False
Explanation: Self-loop: a guest 'knows' themselves and cannot be consistently seated.
Input: ([[1], [0], [3], [2]],)
Expected Output: True
Explanation: Two separate edges (disconnected components), each 2-colorable independently.
Input: ([[1, 3], [0, 2], [1, 3], [0, 2]],)
Expected Output: True
Explanation: A 4-cycle (even cycle) is bipartite: alternate groups around the cycle.
Input: ([[1, 2, 3], [0], [0], [0, 4], [3]],)
Expected Output: True
Explanation: A tree-like structure with a branch is always bipartite.
Input: ([[1, 1], [0, 0]],)
Expected Output: True
Explanation: Duplicate edges are harmless; still a single bipartite edge between two guests.
Hints
- Two groups + 'same group must not know each other' is exactly a graph 2-coloring problem. The answer is 'is the graph bipartite?'
- BFS or DFS from each unvisited node, assigning the opposite color to every neighbor. A conflict (a neighbor already has the same color) means it is impossible.
- Iterate the outer loop over ALL nodes so disconnected components are each colored. A self-loop is an instant failure since the node would need a different color from itself.