DSA Factory
Free Graphs lessonsGraphs · Stage 8 · Cycles and colouring · Step 3

Splitting into two teams

Decide whether people with conflicts can be split into two teams so that nobody shares a team with someone they clash with. About 15 minutes.

Forced choices

You are organising a game. Some pairs of people don't get along, and you want two teams where no team contains a pair that clashes. Can it be done?

Start with anyone and put them in team 0. Everyone they clash with must go in team 1. Everyone those people clash with must go back in team 0, and so on. The choices are forced, so you simply spread them out like a ripple, handing each new person the opposite team of the person who reached them.

Opposite team: each person gets the other team from who reached them.
Forced: inside one connected group there is no choice.
In code
colour = [-1] * n
colour[start] = 0
colour[nxt] = 1 - colour[node]
Lines mean 'don't get along'. Team 0 and team 1 are shown under each person.
0team 01234

Start with person 0 and put them in team 0.

Move 1 of 4

Spot the clash

Keep going until every person has a team. The only thing that can go wrong is when you look at a person you clash with, they already have a team, and it is the same as yours. Then both of you would be forced onto the same team, so no split exists.

People who clash with nobody in your group start their own ripple. Start a new one from every person without a team, so separate groups are each checked.

Same team and clash: the split is impossible.
Every piece: start from each person with no team yet.
In code
if colour[nxt] == colour[node]:
    return False
Quick check

Three people all clash with each other (a triangle). Can they be split into two teams?

  1. ANo. Person 1 goes in team 0, so 2 and 3 are forced into team 1, where they clash
  2. BYes, two in one team and one in the other
  3. CIt depends who goes first
Show the answer

No. Person 1 goes in team 0, so 2 and 3 are forced into team 1, where they clash. Any loop with an odd number of people forces two clashing people onto the same team.

Your problem

Two teams

There are n people, numbered 0 to n − 1. clashes[i] = [a, b] means person a and person b do not get along. Return true if the people can be split into two teams so that no two people who clash are on the same team, and false otherwise. A team may be empty.

Example
n = 5, clashes = [[0, 1], [0, 3], [1, 2], [2, 3], [3, 4]] → true

1 ≤ n ≤ 100,000 · 0 ≤ clashes ≤ 200,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve