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. Over the year she has learned which pairs of kids cannot sit near each other without trouble, and she wants every such pair on different buses. Buses are big, so there is no limit on how many kids ride in each.

Some lists are impossible. If Ana clashes with Ben, Ben with Cara, and Cara with Ana, then whichever bus Ana takes, one of the other two has to join her. The teacher wants to know before she makes the seating plan.

Your task

Write canSplit(n, clashes). The 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 so that no clashing pair shares 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 every way to assign the kids: each kid gets bus A or B, so there are 2n assignments, and check each against the clash list.

With 40 kids that is already over a trillion assignments, and n can be 2,000. Almost all of that work 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