Python coding

Split rivals into two teams

There are n players numbered 0 to n - 1, and each pair [a, b] in rivals means players a and b refuse to play on the same team. Return True if the players can be split into two teams (one of them may be empty) so that no two rivals share a team, otherwise False.

n ≥ 1. In every pair a ≠ b; a pair may repeat, and some players may have no rivals at all.

Besides the tests, one large input (20 players) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • can_split(4, [[0,1],[1,2],[2,3],[3,0]]) → true
  • can_split(3, [[0,1],[1,2],[2,0]]) → false
  • can_split(5, [[0,1],[2,3],[3,4],[4,2]]) → false
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Players are nodes and rivalries are edges. A valid split is a two-coloring: every edge must join two different colors.

Hint 2

Put one player on team 0, then BFS: each rival without a team gets the opposite one. A rival already on your own team means no split exists.

Hint 3

The rivalry graph can come in several pieces: start a new BFS from every player who has no team yet.

Solution and why it works
pythonO(n + m), m = rivalries · O(n + m)
from collections import deque


def can_split(n: int, rivals: list[list[int]]) -> bool:
    adj = [[] for _ in range(n)]
    for a, b in rivals:
        adj[a].append(b)
        adj[b].append(a)
    team = [-1] * n
    for start in range(n):
        if team[start] != -1:
            continue
        team[start] = 0                          # a new group: its first player picks freely
        queue = deque([start])
        while queue:
            u = queue.popleft()
            for v in adj[u]:
                if team[v] == -1:
                    team[v] = 1 - team[u]        # a rival is forced onto the other team
                    queue.append(v)
                elif team[v] == team[u]:
                    return False
    return True

In a connected group, the first player's team forces everyone else's: a rival goes on the other team, a rival's rival back on yours. So BFS assigns the teams and fails exactly when an edge joins two players on the same team, which happens on an odd cycle (three mutual rivals can't be split). Start a BFS from every player without a team, or a second group is never checked. Trying every split is 2ⁿ; assigning teams pair by pair in input order, without propagating, rejects splits that exist.