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
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | A triangle | Not run | |
| 3 | A ring of 5 | Not run | |
| 4 | A ring of 6 | Not run | |
| 5 | No edges | Not run | |
| 6 | Two parts | Not run | |
| 7 | An edge given twice | Not run | |
| 8 | The odd cycle is far away | Not run | |
| 9 | A ring of 100,001 | Not run | |
| 10 | A path of 100,000 | Not run | |
| 11 | 170,000 edges across | Not run | |
| 12 | One edge spoils it | Not run |