Two Buses for the Trip

Easybreadth-first searchAlso known as Is Graph Bipartite?

A teacher is taking the class to the science museum in two buses. She knows which pairs of kids cause trouble together and wants every such pair on different buses. Either bus can hold any number of kids.

Some lists are impossible. If Ana clashes with Ben, Ben with Cara, and Cara with Ana, one of the other two must share Ana's bus.

Your task

Write canSplit(n, clashes). Kids are numbered 0 to n - 1. Each [a, b] in clashes means kids a and b must ride different buses. Return true if every kid can be put on one of the two buses with no clashing pair sharing a bus, otherwise false.

A kid with no clashes can ride either bus. The same pair may be listed more than once.

canSplit(n: int, clashes: int[][]) → bool

Examples

Example 1
Input
n = 4
clashes = [[0, 1], [1, 2], [2, 3], [3, 0]]
Output
true
Why

The clashes form a loop of four. Put 0 and 2 on bus A, and 1 and 3 on bus B. Every clash crosses between the buses.

Example 2
Input
n = 3
clashes = [[0, 1], [1, 2], [2, 0]]
Output
false
Why

The triangle from the story. 0 on bus A forces 1 onto B, which forces 2 onto A, but 2 clashes with 0. No assignment works.

Constraints

  • 1 ≤ n ≤ 2,000
  • 0 ≤ clashes.length ≤ 5,000
  • 0 ≤ a, b < n and a ≠ b
Start with brute force

Try all 2n ways to give each kid bus A or B, and check each against the clash list.

With 40 kids that is over a trillion assignments, and n can be 2,000. Almost all of it is wasted, because placing one kid forces everyone connected to them.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code