KatInterview

Two Teams With Rival Pairs Kept Apart

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsgraphbipartitebfs

Last 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 <= 2000
  • 0 <= len(rivalries) <= 10^4
  • len(rivalries[i]) == 2
  • 1 <= 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.