GRPH-P6

Two teams, or an odd cycle

Practice 6 of 7Graphs12 tests

The problem

There are n people, numbered 0 to n − 1. Each edge (u, v) joins two people who must be on different teams. If two teams are possible, return (True, side), where side is a list of n numbers, each 0 or 1, and every edge joins a 0 to a 1.

If two teams are impossible, prove it: return (False, cycle), where cycle lists an odd number of different people, each joined by an edge to the next, and the last joined to the first (lesson 6).

two_teams(5, [(0, 1), (1, 2), (2, 3), (3, 0), (3, 4)])
# (True, [0, 1, 0, 1, 0])
two_teams(3, [(0, 1), (1, 2), (2, 0)])
# (False, [0, 1, 2])

Any correct answer is accepted. The tests check every edge of your teams, or follow your cycle and count its people. No edge joins a person to themselves; an edge may be listed twice.

Limits

  • Up to 100,001 people and 170,000 edges.
  • Paths and cycles can be 100,000 people long, so a recursive search is too deep. The big tests have 3 seconds each.

Builds on GRPH-6 Bipartite graphs.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

12 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2A triangleNot run
3A ring of 5Not run
4A ring of 6Not run
5No edgesNot run
6Two partsNot run
7An edge given twiceNot run
8The odd cycle is far awayNot run
9A ring of 100,001Not run
10A path of 100,000Not run
11170,000 edges acrossNot run
12One edge spoils itNot run