Two Teams With Rival Pairs Kept Apart
Trees & GraphsAuto-graded · 23 test casesLast updated
Decide whether a set of people can be placed into two teams so that no rival pair shares a team, which tests graph 2-coloring across possibly disconnected components.
Two Teams With Rival Pairs Kept Apart
A event organizer has n participants, numbered 1 through n. They must be assigned to one of two teams. Some participants are rivals, and rivals must never be placed on the same team.
You are given the integer n and a list rivalries. Each entry rivalries[i] = [a, b] states that participants a and b are rivals. Rivalry is symmetric: it does not matter which of the two is listed first, the two must simply end up on different teams.
Return True if there is at least one way to assign every participant to a team so that no rival pair shares a team. Return False otherwise.
Rules
- Every participant belongs to exactly one of the two teams.
- A team may be of any size, including empty.
- A participant who appears in no rivalry may be placed on either team.
- Only the existence of a valid assignment matters, not the assignment itself.
Constraints
1 <= n <= 20000 <= len(rivalries) <= 10^4len(rivalries[i]) == 21 <= rivalries[i][0] < rivalries[i][1] <= n- No pair appears more than once in
rivalries.
Examples
Example 1
Input: can_form_two_teams(4, [[1, 2], [2, 3], [3, 4], [1, 4]])
Output: True
Example 2
Input: can_form_two_teams(6, [[1, 2], [3, 4], [4, 5], [3, 5]])
Output: False
Example 3
Input: can_form_two_teams(3, [])
Output: True
Hints
Hint 1
Think of each participant as a node and each rivalry as an undirected connection between two nodes. What property must the resulting graph have for a two-team split to exist?
Hint 2
Try to assign teams greedily: once you place one participant, every rival of theirs is forced onto the opposite team. Propagate these forced choices with a BFS or an iterative stack.
Hint 3
The graph may be split into several disconnected pieces, and some participants have no rivals at all. Start a fresh traversal from every participant that has not been assigned yet, and report failure as soon as an edge joins two participants forced onto the same team.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each participant as a vertex and each rivalry as an undirected edge. Splitting people into two teams so that no rival pair shares a team is exactly the definition of a bipartite graph, so the task is to check whether the graph is 2-colorable.
- Build an adjacency list, adding every rivalry in both directions.
- Keep a
colorarray:-1means unassigned,0and1are the two teams. - For every participant from
1tonwho is still unassigned, give them color0and run a BFS. - When visiting
u, examine each neighborv:- If
vis unassigned, give it the opposite color and enqueue it. - If
vhas the same color asu, two rivals are forced together, so returnFalse.
- If
- If all components finish without conflict, return
True.
Why it is correct
- False is correct. Within a connected component, once the starting color is chosen (the choice is symmetric), every other color is forced: neighbors take the opposite color, and so on. A conflict means an edge joins two vertices forced to the same color, which happens exactly when the component contains an odd cycle. Odd cycles cannot be alternately colored with two colors, so no valid split exists.
- True is correct. Every edge is checked from at least one endpoint after both ends are colored, either by assigning the opposite color or by verifying the colors differ. So every rivalry connects the two teams.
- Components are independent. No edge crosses components, so the arbitrary starting color of one component cannot conflict with another. Participants with no rivals form single-vertex components and simply get color
0.
The outer loop over all participants is essential; without it, an odd cycle in an unvisited component would be missed.
Complexity
- Time:
O(n + m), wherem = len(rivalries). Each vertex is enqueued once and each adjacency entry is scanned once. - Space:
O(n + m)for the adjacency list, color array and queue.
Reference solution
from collections import deque
from typing import List
def can_form_two_teams(n: int, rivalries: List[List[int]]) -> bool:
adj = [[] for _ in range(n + 1)]
for a, b in rivalries:
adj[a].append(b)
adj[b].append(a)
color = [-1] * (n + 1)
for start in range(1, n + 1):
if color[start] != -1:
continue
color[start] = 0
q = deque([start])
while q:
u = q.popleft()
for v in adj[u]:
if color[v] == -1:
color[v] = color[u] ^ 1
q.append(v)
elif color[v] == color[u]:
return False
return True